forked from benibela/rcmdline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrcmdline.pas
1309 lines (1184 loc) · 48.7 KB
/
rcmdline.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
{Copyright (C) 2006 Benito van der Zander
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
(*** @abstract(
Command line reader
)*)
unit rcmdline;
interface
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}
//{$define unitcheck_rcmdline}
uses sysutils; //for exceptions
type
TStringArray=array of string;
TLongintArray=array of longint;
TFloatArray=array of extended;
TBooleanArray=array of boolean;
TCommandLineReaderLanguage=(clrlEnglish,clrlGerman);
TCommandLineReaderShowError=procedure (errorDescription: string) of object;
ECommandLineParseException=class(Exception);
TKindOfProperty=(kpStr,kpFile,kpInt,kpFloat,kpFlag);
TProperty=record
category: string;
name,desc,strvalue,strvalueDefault:string;
strenumeration: TStringArray;
found: boolean;
abbreviation: char;
case kind: TKindOfProperty of
kpStr,kpFile: ();
kpInt: (intvalue, intvalueDefault: longint);
kpFloat: (floatvalue, floatvalueDefault: extended);
kpFlag: (flagvalue,flagdefault: boolean)
end;
PProperty=^TProperty;
TOptionReadEvent = procedure (sender: TObject; const name, value: string) of object;
TOptionInterpretationEvent = procedure (sender: TObject; var name, value: string; const args: TStringArray; var argpos: integer) of object;
{ TCommandLineReader }
(*** @abstract(
A command line reader class that checks for valid arguments and automatically prints a formatted help.
)
@br
@br
Usage: @orderedList(
@item( Declare all allowed arguments with the corresponding DeclareXXXX functions )
@item( (optional) Call parse to explicitely read the actual command line )
@item( Use readXXX to read a declared argument )
)
On the command line arguments can be given in different ways, e.g.
@code(--name=value), @code(/name=value), @code(--name value), @code(/name value) @br
Declared flags can be changed with @code(--enable-flag) or @code(--disable-flag) or @code(--flag) where
latter option negates the default value.@br
File are checked for spaces, so it is not always necessary to include them in quotes.
*)
TCommandLineReader=class
protected
parsed{,searchNameLessFile,searchNameLessInt,searchNameLessFloat,searchNameLessFlag}: boolean;
propertyArray: array of TProperty;
nameless: TStringArray;
currentDeclarationCategory: String;
FOnOptionRead: TOptionReadEvent;
FOnOptionInterpretation: TOptionInterpretationEvent;
FAllowOverrides: boolean;
function findProperty(name:string):PProperty;
function declareProperty(name,description,default:string;kind: TKindOfProperty):PProperty;
procedure raiseErrorWithHelp(message: string);
procedure parseSingleValue(var prop: TProperty);
class function splitCommandLine(s: string; skipFirst: boolean): TStringArray;
public
language:TCommandLineReaderLanguage; //not implemented yet
onShowError: TCommandLineReaderShowError;
automaticalShowError: boolean;
allowDOSStyle: boolean;
constructor create;
destructor destroy;override;
//** Returns the option summary printed by unknown errors
function availableOptions:string;
//** Resets all options to their default values
procedure reset();
//** Reads the standard command line parameters
procedure parse(autoReset: boolean = true);overload;virtual;
//** Reads the command line parameters from the string s
procedure parse(const s:string; skipFirst: boolean = false; autoReset: boolean = true);overload;virtual;
//** Reads the command line parameters from the array args
procedure parse(const args:TStringArray; autoReset: boolean = true);overload;virtual;
//** Adds a new option category. The category is just printed in the --help output
procedure beginDeclarationCategory(category: string);
//**DeclareFlag allows the use of flags @br
//**Example: @br
//** @code(declareFlag('flag','f',true);) @br
//** Following command-line options are always possible @br
//** --enable-flag => flag:=true @br
//** --disable-flag => flag:=false @br
//** --flag => flag:=not default @br
//** -xfy => flag:=not default
procedure declareFlag(const name,description:string;flagNameAbbreviation:char;default:boolean=false);overload;
procedure declareFlag(const name,description:string;default:boolean=false);overload;
//**DeclareFile allows the use of a file name @br
//**Example: @br
//** @code(declareFile('file');) @br
//** Following command-line options are possible @br
//** --file C:\test => file:=C:\test @br
//** --file 'C:\test' => file:=C:\test @br
//** --file "C:\test" => file:=C:\test @br
//** --file='C:\test' => file:=C:\test @br
//** --file="C:\test" => file:=C:\test @br
//** --file C:\Eigene Dateien\a.bmp => file:=C:\Eigene @br
//** or file:=C:\Eigene Dateien\a.bmp, @br
//** if C:\Eigene does not exist
procedure declareFile(const name,description:string;default:string='');overload;
//**DeclareXXXX allows the use of string, int, float, ...
//**Example: @br
//** @code(declareInt('property');) @br
//** Following command-line options are possible @br
//** --file 123 => file:=123 @br
//** --file '123' => file:=123 @br
//** --file "123" => file:=123 @br
//** --file='123' => file:=123 @br
//** --file="123" => file:=123 @br
procedure declareString(const name,description:string;value: string='');overload;
procedure declareInt(const name,description:string;value: longint=0);overload;
procedure declareFloat(const name,description:string;value: extended=0);overload;
//**Allows to use -abbreviation=... additionally to --originalName=... @br
//**With windows style /abbreviation and /originalName will behave in the same way
//**(only single letter abbreviations are allowed like in unix commands)
procedure addAbbreviation(const abbreviation: char; const originalName: string = '');
//**Only allow certain values for argument @code(originalName)
procedure addEnumerationValues(const originalName: string; const enumeration: array of string);
//**Only allow certain values for the last argument
procedure addEnumerationValues(const enumeration: array of string);
protected
procedure addEnumerationValues(p: PProperty; const enumeration: array of string);
public
//** Reads a previously declared string property
function readString(const name:string):string; overload;
//** Reads a previously declared int property
function readInt(const name:string):longint;overload;
//** Reads a previously declared float property
function readFloat(const name:string):extended; overload;
//** Reads a previously declared boolean property
function readFlag(const name:string):boolean;overload;
//** Tests if a declared property named name has been read
function existsProperty(const name:string):boolean;
//** Reads all file names that are given on the command line and do not belong to an declared option (doesn't check for non existing files, yet)
function readNamelessFiles():TStringArray;
//** Reads all strings that are given on the command line and do not belong to an declared option
function readNamelessString():TStringArray;
//** Reads all integers that are given on the command line and do not belong to an declared option
function readNamelessInt():TLongintArray;
//** Reads all floats that are given on the command line and do not belong to an declared option
function readNamelessFloat():TFloatArray;
//** Reads all booleans (true, false) that are given on the command line and do not belong to an declared option
function readNamelessFlag():TBooleanArray;
//** Event called when an option has been parsed. (e.g. to read all values if an option is given multiple times)
//** @code(name) contains the declared name of the property (not necessarily the same as the name the user used)
//** @code(value) the value read
property onOptionRead: TOptionReadEvent read FOnOptionRead write FOnOptionRead;
//** Event called when an option is being parsed. (e.g. to allow custom abbreviations of names)@br
//** @code(name) contains the read name of the property@br
//** @code(value) the value read; or the next value for boolean options (which will ignored)@br
//** @code(args) all arguments@br
//** @code(argpos) the current argument @br
property onCustomOptionInterpretation: TOptionInterpretationEvent read FOnOptionInterpretation write FOnOptionInterpretation;
//** If the same option may be given multiple times. Only the last value is remained.
property allowOverrides: boolean read FAllowOverrides write FAllowOverrides;
end;
implementation
{$ifdef win32}{$define windows}{$endif} //Delphi 4 does not know the windows-define
{$ifdef MSWINDOWS}{$define windows}{$endif} // for 64-bit compilers
uses {$ifdef unitcheck_rcmdline}classes,{$endif}
{$ifdef windows}windows
{$else}baseunix,termio {$endif}
;
function strJoin(a: TStringArray): string;
var
i: Integer;
begin
result := '';
if length(a) = 0 then exit;
result := a[0];
for i := 1 to high(a) do
result := result + ', ' + a[i];
end;
{$ifdef fpc}
function equalCaseInseq(const a, b: string): boolean;
begin
result := SameText(a,b);
end;
{$else}
function equalCaseInseq(const a, b: string): boolean;
begin
result := (length(a) = length(b)) and (strLiComp(pchar(a), pchar(b), length(a)) = 0);
end;
const LineEnding = #13#10;
{$endif}
function getTerminalWidth: integer;
{$ifdef windows}
var csbi: TCONSOLESCREENBUFFERINFO;
handle: THANDLE;
{$else}
var winsize: TWinSize;
{$endif}
begin
result := 80;
{$ifdef windows}
handle := GetStdHandle(STD_OUTPUT_HANDLE);
if handle = INVALID_HANDLE_VALUE then exit;
if not GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), csbi) then exit;
result := csbi.srWindow.Right - csbi.srWindow.Left + 1;
{$else}
if FpIOCtl(StdOutputHandle, TIOCGWINSZ, @winsize) = 0 then
result := winsize.ws_col;
{$endif}
if result < 10 then result := 80;
end;
constructor TCommandLineReader.create;
begin
parsed:=false;
{$IFDEF windows}
allowDOSStyle:=true;
{$ELSE}
allowDOSStyle:=false;
{$ENDIF}
language:=clrlEnglish;
onShowError:=nil;
{searchNameLessFile:=false;
searchNameLessInt:=false;
searchNameLessFloat:=false;
searchNameLessFlag:=false;}
automaticalShowError:=not IsLibrary;
FAllowOverrides:=false;
end;
destructor TCommandLineReader.destroy;
begin
inherited;
end;
function TCommandLineReader.availableOptions: string;
//from bbutils
function strWrap(const Line: string; MaxCol: Integer; lineBreak: string): string;
var res: string;
procedure add(x: string);
begin
if res = '' then res := x
else res := res + lineBreak + x;
end;
const BreakChars = [' ',#9];
var i: integer;
lastTextStart, lastBreakChance: integer;
tempBreak: Integer;
begin
result := '';
lastTextStart:=1;
lastBreakChance:=0;
result := '';
for i := 1 to length(line) do begin
if line[i] in [#13,#10] then begin
if lastTextStart > i then continue;
add(copy(Line,lastTextStart,i-lastTextStart));
lastTextStart:=i+1;
if (i < length(line)) and (line[i] <> line[i+1]) and (line[i+1] in [#13, #10]) then inc(lastTextStart);
end;
if (i < length(line)) and (line[i+1] in BreakChars) then begin
lastBreakChance:=i+1;
if lastTextStart = lastBreakChance then inc(lastTextStart); //merge seveal break characters into a single new line
end;
if i - lastTextStart + 1 >= MaxCol then begin
if lastBreakChance >= lastTextStart then begin
tempBreak := lastBreakChance;
while (tempBreak > 1) and (line[tempBreak-1] in BreakChars) do dec(tempBreak); //remove spaces before line wrap
add(copy(Line,lastTextStart,tempBreak-lastTextStart));
lastTextStart:=lastBreakChance+1;
end else begin
add(copy(Line, lastTextStart, MaxCol));
lastTextStart:=i+1;
end;
end;
end;
if lastTextStart <= length(line) then add(copy(line, lastTextStart, length(line)));
result := res;
end;
function mydup(count: integer): string;
var
i: Integer;
begin
result := '';
for i := 1 to count do result := result + ' ';
end;
var i:integer;
cur, description, dupped: String;
j: Integer;
p: integer;
names: array of string;
multiline : boolean;
maxLen: Integer;
category: String;
terminalWidth: Integer;
pseudoLineBreak: String;
begin
names := nil;
setlength(names, length(propertyArray));
maxLen := 0;
multiline:=false;
category := '';
terminalWidth := getTerminalWidth;
for i:=0 to high(propertyArray) do begin
cur:='--'+propertyArray[i].name;
case propertyArray[i].kind of
kpFlag: ;
kpInt: cur := cur + '=<int> ';
kpFloat: cur := cur + '=<float> ';
kpStr: cur := cur + '=<string> ';
kpFile: cur := cur + '=<file> ';
else cur:=cur+'=';
end;
if propertyArray[i].abbreviation<>#0 then cur := cur + ' or -'+propertyArray[i].abbreviation;
names[i] := cur;
if length(cur) > maxLen then maxLen := length(cur);
multiline:=multiline or (pos(LineEnding, propertyArray[i].desc) > 0) or (length(propertyArray[i].strenumeration) > 0);
end;
dupped := '';
for j:=1 to maxLen do dupped := dupped + ' ';
;
result:='';
for i:=0 to high(propertyArray) do begin
if propertyArray[i].category <> category then begin
category := propertyArray[i].category;
result := result + LineEnding + LineEnding + category + LineEnding+LineEnding;
end;
cur:=names[i];
if category <> '' then cur := ' ' + cur;
pseudoLineBreak := LineEnding+dupped;
if category <> '' then pseudoLineBreak := pseudoLineBreak + ' ';
pseudoLineBreak := pseudoLineBreak + #9;
description := propertyArray[i].desc;
if length(propertyArray[i].strenumeration) > 0 then
description := description + LineEnding + 'Allowed values: ' + strJoin(propertyArray[i].strenumeration);
if (not multiline or ( pos(LineEnding, description) = 0 )) and (length(description)+maxLen+10 < terminalWidth) then
cur := cur + mydup(maxLen - length(cur)) + #9 + description + LineEnding
else begin
cur := cur + mydup(maxLen - length(cur));
p := pos(LineEnding, description);
while p > 0 do begin
cur := cur + #9 + strWrap(copy(description, 1, p - 1), terminalWidth - 10 - maxLen, pseudoLineBreak) + LineEnding + dupped;
if category <>' ' then cur := cur + ' ';
delete(description, 1, p + length(LineEnding) - 1);
p := pos(LineEnding, description);
end;
cur := cur + #9 + strWrap(description, terminalWidth - 10 - maxLen, pseudoLineBreak) + LineEnding;
end;
result:=result+cur;
end;
end;
procedure TCommandLineReader.reset();
var
i: Integer;
begin
SetLength(nameless,0);
for i:=0 to high(propertyArray) do begin
with propertyArray[i] do begin
if found then begin
found:=false;
case kind of
kpStr,kpFile: strvalue := strvalueDefault;
kpInt: intvalue:=intvalueDefault;
kpFloat: floatvalue:=floatvalueDefault;
kpFlag: flagvalue:=flagdefault;
end;
end;
end;
end;
end;
procedure TCommandLineReader.parse(autoReset: boolean = true);
{$ifndef windows}
var args: TStringArray;
i: Integer;
{$endif}
begin
if Paramcount = 0 then exit;
{$ifdef windows}
parse(string(getcommandline), true, autoReset);
{$else}
args := nil;
setlength(args, Paramcount);
for i:=0 to high(args) do args[i] := paramstr(i+1);
parse(args, autoReset);
{$endif}
end;
procedure TCommandLineReader.parse(const s:string; skipFirst: boolean = false; autoReset: boolean = true);
var
args: TStringArray;
begin
args := splitCommandLine(s, skipFirst);
parse(args, autoReset);
end;
procedure TCommandLineReader.parse(const args: TStringArray; autoReset: boolean = true);
var a: string;
procedure raiseError(message: string);
begin
raiseErrorWithHelp('Error: '+message+LineEnding+'(error occured when reading argument: '+a+')');
end;
procedure raiseNoProperty(name: string);
begin
if (name = 'help') or (name = '?') then raiseErrorWithHelp('')
else raiseError('Unknown option: '+name);
end;
function findPropertyIndex(const name: string; allowLong, allowAbbreviation, allowMissing: boolean): integer;
var
i: Integer;
begin
if allowLong then
for i:=0 to high(propertyArray) do
if equalCaseInseq(propertyArray[i].name, name) then begin
result:=i;
exit;
end;
if allowAbbreviation then
for i:=0 to high(propertyArray) do
if propertyArray[i].abbreviation = name then begin
result:=i;
exit;
end;
if allowMissing then result := -1
else raiseNoProperty(name)
end;
var argpos: Integer;
procedure setPropertyFromStringValue(currentPropertyIndex: integer; value: string);
var
i: Integer;
currentProperty: PProperty;
found: Boolean;
begin
currentProperty := @propertyArray[currentPropertyIndex];
if length(currentProperty^.strenumeration) > 0 then begin
found := false;
for i := 0 to high(currentProperty^.strenumeration) do
if currentProperty^.strenumeration[i] = value then begin
found := true;
break;
end;
if not found then raiseError('Invalid value for: '+currentProperty^.name + LineEnding + 'Allowed values are: ' + strjoin(currentProperty^.strenumeration));
end;
currentProperty^.strvalue := value;
if (currentProperty^.kind = kpFile) then begin
for i := 0 to length(args) - argpos do begin
if FileExists(value) then begin
inc(argpos, i);
currentProperty^.strvalue := value;
break;
end;
if i = length(args) - argpos then break; //not found
value := value + ' ' + args[argpos + i];
end;
end else parseSingleValue(currentProperty^);
if not FAllowOverrides and currentProperty^.found then raiseError('Duplicated option: '+currentProperty^.name);
currentProperty^.found:=true;
if assigned(onOptionRead) then onOptionRead(self,currentProperty^.name, currentProperty^.strvalue);
end;
function invertedFlag(flagId: integer): string;
begin
if propertyArray[flagId].flagvalue then result := 'false' else result := 'true';
end;
var currentProperty:longint;
i:integer;
index: integer;
name: String;
value: String;
j: Integer;
noFlagExpansion: Boolean;
allowAbbreviation: Boolean;
weAreDoneInterpreting: Boolean;
begin
if autoReset then reset();
parsed:=true; //mark as parsed, so readXXX can be used within the event called by onOptionRead
weAreDoneInterpreting := false;
argpos := 0;
while argpos < length(args) do begin
a := args[argpos];
inc(argpos);
if a = '' then continue;
if a = '--' then begin
if Assigned(FOnOptionInterpretation) then begin
value := '';
FOnOptionInterpretation(self, a, value, args, argpos);
if a <> '--' then continue;
end;
weAreDoneInterpreting:=true;
continue;
end;
allowAbbreviation := true; //for special handling of DOS style args. /x is prefered to be --x but can fallback to abbreviated -x
if not weAreDoneInterpreting and (a <> '-') and (a <> '--')
and ((a[1] = '-') or (allowDOSStyle and (a[1]='/'))) then begin
//Start of property name
if (length(a) > 1) and ((a[1]='/') or (a[2]='-') ) then begin //long property
if (a[2]='-') then begin
delete(a, 1, 2);
allowAbbreviation := false;
end else delete(a, 1, 1);
if a = '' then continue;
if (StrLIComp(@a[1],'enable-',7) = 0)or
(StrLIComp(@a[1],'disable-',8) = 0) then begin
//long flag
if a[1]='e' then begin
delete(a, 1, 7);
value := 'true';
end else begin
delete(a, 1, 8);
value := 'false';
end;
if (propertyArray[findPropertyIndex(a, true, false, false)].kind <> kpFlag) then raiseError('No flag: '+a);
a := a + '=' + value; //this will be split again in the next step, but simplifies the code
end;
end else begin
noFlagExpansion := false;
for j:=2 to length(a) do begin //2 to skip leading -
i:=findPropertyIndex(a[j], false, true, false);
if propertyArray[i].kind=kpFlag then begin
setPropertyFromStringValue(i, invertedFlag(i));
end else if (j = length(a)) or (a[j+1] = '=') then begin
noFlagExpansion := true;
a := propertyArray[i].name + copy(a, j+1, length(a) - j);
break
end else raiseError('Invalid abbreviation: '+a[j]+ LineEnding +'(use -- or / for arguments)');
end;
if not noFlagExpansion then continue;
end;
//a now contains a long property something or something=value
index := pos('=', a);
if index > 0 then begin
name := copy(a, 1, index - 1);
value := copy(a, index + 1, length(a) - index);
currentProperty := findPropertyIndex(name, true, allowAbbreviation, true);
if currentProperty >= 0 then name := propertyArray[currentProperty].name;
end else begin
name := a;
currentProperty := findPropertyIndex(name, true, allowAbbreviation, true);
if currentProperty >= 0 then name := propertyArray[currentProperty].name;
if (currentProperty >= 0) and (propertyArray[currentProperty].kind = kpFlag) then value := invertedFlag(currentProperty)
else if (argpos < length(args)) then begin
value := args[argpos];
inc(argpos);
end else value := '';
end;
if Assigned(FOnOptionInterpretation) then FOnOptionInterpretation(self, name, value, args, argpos);
j := findPropertyIndex(name, true, false, false);
if (index = 0) and (value = '') and (argpos >= length(args)) then
raiseError('No value for option '+name+' given');
setPropertyFromStringValue(j, value);
end else begin
if not weAreDoneInterpreting and Assigned(FOnOptionInterpretation) then begin
name := '';
FOnOptionInterpretation(self, name, a, args, argpos);
if name <> '' then begin
setPropertyFromStringValue(findPropertyIndex(name, true, false, false), value);
continue;
end;
end;
//value without variable name
SetLength(nameless,length(nameless)+1);
nameless[high(nameless)] := a;
if assigned(onOptionRead) then onOptionRead(self,'', a);
end;
end;
{debug things: for i:= 0 to high(propertyArray) do
if propertyArray[i].found then begin
write(propertyArray[i].name , ' => ', propertyArray[i].strvalue);
if propertyArray[i].kind =kpFlag then writeln( '(',propertyArray[i].flagvalue,')')
else writeln;
end;
for i:= 0 to high(nameless) do writeln('no: ', nameless[i]);}
end;
procedure TCommandLineReader.beginDeclarationCategory(category: string);
begin
currentDeclarationCategory := category;
end;
function TCommandLineReader.findProperty(name:string):PProperty;
var i:integer;
begin
name:=lowercase(name);
for i:=0 to high(propertyArray) do
if propertyArray[i].name=name then begin
result:=@propertyArray[i];
exit;
end;
raise ECommandLineParseException.Create('Property not found: '+name);
end;
function TCommandLineReader.declareProperty(name,description,default:string;kind: TKindOfProperty):PProperty;
begin
SetLength(propertyArray,length(propertyArray)+1);
result:=@propertyArray[high(propertyArray)];
result^.category:=currentDeclarationCategory;
result^.name:=lowercase(name);
result^.desc:=description;
result^.strvalue:=default;
result^.kind:=kind;
end;
procedure TCommandLineReader.raiseErrorWithHelp(message: string);
var errorMessage: string;
begin
if assigned(onShowError) or automaticalShowError then begin
errorMessage:=message+LineEnding;
if length(propertyArray)=0 then
errorMessage:=errorMessage+LineEnding+LineEnding+'You are not allowed to use command line options starting with -'
else
errorMessage:=errorMessage+ LineEnding+LineEnding+'The following command line options are valid: '+LineEnding+LineEnding+ availableOptions;
end;
if assigned(onShowError) then
onShowError(errorMessage);
if automaticalShowError then begin
if system.IsConsole then begin
writeln(errorMessage);
halt;
end;
{else
ShowMessage(errorMessage);} //don't want to link against showMessage in console applications.
;
end;
raise ECommandLineParseException.create(message);
end;
procedure TCommandLineReader.parseSingleValue(var prop: TProperty);
begin
try
case prop.kind of
kpInt: prop.intvalue:=StrToInt(prop.strvalue);
kpFloat: prop.floatvalue:=StrToFloat(prop.strvalue);
kpFlag: begin
prop.flagvalue:=equalCaseInseq(prop.strvalue, 'true');
if not prop.flagvalue and not equalCaseInseq(prop.strvalue, 'false') then
raiseErrorWithHelp('Only "true" and "false" are valid flag values for option '+prop.name);
end;
end;
except
raiseErrorWithHelp('Invalid value: '+prop.strvalue+' for option '+prop.name);
end;
end;
class function TCommandLineReader.splitCommandLine(s: string; skipFirst: boolean): TStringArray;
var args: TStringArray;
cmd: pchar;
marker: pchar;
stringstart: Char;
hasEscapes, newArgument: boolean;
const SPACE = [' ',#9];
procedure pushMarked;
var
addLen: longint;
begin
if marker = nil then exit;
if skipFirst then begin
skipFirst:=false;
marker := nil;
exit;
end;
if newArgument then begin
setlength(args, length(args)+1);
newArgument:=false;
end;
addLen := cmd - marker;
if addLen <= 0 then begin
marker := nil;
exit;
end;
setlength(args[high(args)], length(args[high(args)]) + addLen);
move(marker^, args[high(args)][ length(args[high(args)]) - addLen + 1 ], SizeOf(Char) * addLen);
if hasEscapes then begin
args[high(args)] := StringReplace(StringReplace(args[high(args)], '\'+stringstart, stringstart, [rfReplaceAll]),
'\\', '\', [rfReplaceAll]); //todo: are these all cases
hasEscapes := false;
end;
marker := nil;
end;
var backslashCount: integer;
begin
if s = '' then exit;
cmd := @s[1];
marker := nil;
newArgument := true;
hasEscapes := false;
while true do begin
case cmd^ of
' ', #9, #0: begin
pushMarked;
while cmd^ in SPACE do inc(cmd);
if cmd^ = #0 then break;
newArgument := true;
end;
'"', '''': begin
pushMarked;
stringstart := cmd^;
inc(cmd);
marker:=cmd;
backslashCount:=0; hasEscapes := false;
while ((cmd^ <> stringstart) or (odd(backslashCount))) and (cmd^ <> #0) do begin
if cmd^ = '\' then inc(backslashCount)
else backslashCount:=0;
if cmd^ = stringstart then //Special handling of escapes (see below)
hasEscapes:=true;
inc(cmd);
end;
pushMarked;
if cmd^ = #0 then break;
inc(cmd);
end;
'\': begin
//Special handling of escapes:
// Only replace \\ by \, if there is also a \" or \'
// So you can e.g. use \\127.0.0.1\DIR on windows
// as well as a\"b to escape a "
if marker = nil then marker := cmd;
inc(cmd);
if cmd^ in ['"', ''''] then begin
stringstart:=cmd^;
inc(cmd);
hasEscapes:=true;
pushMarked;
end else if not (cmd^ in (SPACE+[#0])) then inc(cmd);
end;
else begin
if marker = nil then marker := cmd;
inc(cmd);
end;
end;
end;
result := args;
end;
procedure TCommandLineReader.declareFlag(const name,description:string;flagNameAbbreviation:char;default:boolean=false);
begin
with declareProperty(name,description,'',kpFlag)^ do begin
flagvalue:=default;
flagdefault:=default;
abbreviation:=flagNameAbbreviation;
end;
end;
procedure TCommandLineReader.declareFlag(const name,description:string;default:boolean=false);
begin
if default<>false then declareFlag(name,description+' (default: true)',#0,default)
else declareFlag(name,description,#0,default);
end;
procedure TCommandLineReader.declareFile(const name,description:string;default:string='');
begin
declareProperty(name,description,default,kpFile)^.strvalueDefault:=default;
end;
procedure TCommandLineReader.declareString(const name,description:string;value: string='');
begin
declareProperty(name,description,value,kpStr)^.strvalueDefault:=value;
end;
procedure TCommandLineReader.declareInt(const name,description:string;value: longint=0);
begin
if value<>0 then
with declareProperty(name,description+' (default: '+IntToStr(value)+')',IntToStr(value),kpInt)^ do begin
intvalue:=value;
intvalueDefault:=intvalue;
end
else with declareProperty(name,description,IntToStr(value),kpInt)^ do begin
intvalue:=value;
intvalueDefault:=intvalue;
end;
end;
procedure TCommandLineReader.declareFloat(const name,description:string;value: extended=0);
begin
with declareProperty(name,description,FloatToStr(value),kpFloat)^ do begin
floatvalue:=value;
floatvalueDefault:=value;
end;
end;
procedure TCommandLineReader.addAbbreviation(const abbreviation: char; const originalName: string = '');
begin
if originalName <> '' then
findProperty(originalName)^.abbreviation:=abbreviation
else begin
if length(propertyArray) = 0 then raise ECommandLineParseException.Create('No properties defined');
propertyArray[high(propertyArray)].abbreviation:=abbreviation;
end;
end;
procedure TCommandLineReader.addEnumerationValues(const originalName: string; const enumeration: array of string);
begin
addEnumerationValues(findProperty(originalName), enumeration);
end;
procedure TCommandLineReader.addEnumerationValues(const enumeration: array of string);
begin
if length(propertyArray) = 0 then raise ECommandLineParseException.Create('No properties defined');
addEnumerationValues(@propertyArray[high(propertyArray)], enumeration);
end;
procedure TCommandLineReader.addEnumerationValues(p: PProperty; const enumeration: array of string);
var
i: Integer;
begin
setlength(p^.strenumeration, length(enumeration));
for i := 0 to high(enumeration) do p^.strenumeration[i] := enumeration[i];
end;
function TCommandLineReader.readString(const name:string):string;
begin
if not parsed then parse;
result:=findProperty(name)^.strvalue;
end;
function TCommandLineReader.readInt(const name:string):longint;
var prop: PProperty;
begin
if not parsed then parse;
prop:=findProperty(name);
if prop^.kind<>kpInt then raise ECommandLineParseException.create('No integer property: '+name);
result:=prop^.intvalue;
end;
function TCommandLineReader.readFloat(const name:string):extended;
var prop: PProperty;
begin
if not parsed then parse;
prop:=findProperty(name);
if prop^.kind<>kpFloat then raise ECommandLineParseException.create('No extended property: '+name);
result:=prop^.Floatvalue;
end;
function TCommandLineReader.readFlag(const name:string):boolean;
var prop: PProperty;
begin
if not parsed then parse;
prop:=findProperty(name);
if prop^.kind<>kpFlag then raise ECommandLineParseException.create('No flag property: '+name);
result:=prop^.flagvalue;
end;
function TCommandLineReader.existsProperty(const name:string):boolean;
begin
if not parsed then parse;
result:=findProperty(name)^.found;
end;
function TCommandLineReader.readNamelessFiles():TStringArray;
begin
Result:=nameless;
end;
function TCommandLineReader.readNamelessString():TStringArray;
begin
result:=nameless;
end;
function TCommandLineReader.readNamelessInt():TLongintArray;
var i,p:integer;
begin
result := nil;
SetLength(result,length(nameless));
p:=0;
for i:=0 to high(nameless) do
try
result[p]:=StrToInt(nameless[i]);
inc(p);
except
end;
SetLength(result,p);
end;
function TCommandLineReader.readNamelessFloat():TFloatArray;
var i,p:integer;
begin
result := nil;
SetLength(result,length(nameless));
p:=0;
for i:=0 to high(nameless) do
try
result[p]:=StrToFloat(nameless[i]);
inc(p);
except
end;
SetLength(result,p);
end;
function TCommandLineReader.readNamelessFlag():TBooleanArray;
var i,p:integer;
begin
result := nil;
SetLength(result,length(nameless));
p:=0;
for i:=0 to high(nameless) do begin
if lowercase(nameless[i])='true' then Result[p]:=true
else if lowercase(nameless[i])='false' then Result[p]:=false
else dec(p);
inc(p);
end;
SetLength(result,p);
end;
{$ifdef unitcheck_rcmdline}
var cmdLineReader: TCommandLineReader;
tsl: tstringlist;
procedure say(s: string);
begin
if IsConsole then writeln(s)
//else ShowMessage(s);
end;
var cmdlinetest: integer = 0;
procedure testSplitCommandLineRaw(line: string; skipFirst: boolean; expected: array of string);
var
args: TStringArray;
i: Integer;
ok: boolean;
begin
args := TCommandLineReader.splitCommandLine(line, skipFirst);
ok := true;
cmdlinetest := cmdlinetest + 1;
if length(args) <> length(expected) then begin
ok := false;
end;
if ok then
for i:=0 to high(args) do
if (args[i] <> expected[i]) then begin