| 1 |
{ |
| 2 |
Copyright 2002-2023 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Processing command-line parameters and options (TParameters, |
| 17 |
single instance Parameters). } |
| 18 |
unit CastleParameters; |
| 19 |
|
| 20 |
{$I castleconf.inc} |
| 21 |
|
| 22 |
interface |
| 23 |
|
| 24 |
uses SysUtils, CastleVectors, CastleUtils, CastleStringUtils; |
| 25 |
|
| 26 |
type |
| 27 |
EInvalidParams = class(EShortErrorMessage); |
| 28 |
EInvalidShortOption = class(EInvalidParams); |
| 29 |
EInvalidLongOption = class(EInvalidParams); |
| 30 |
EWrongOptionArgument = class(EInvalidParams); |
| 31 |
EExcessiveOptionArgument = class(EWrongOptionArgument); |
| 32 |
EMissingOptionArgument = class(EWrongOptionArgument); |
| 33 |
|
| 34 |
TOptionArgument = ( |
| 35 |
{ No arguments allowed. } |
| 36 |
oaNone, |
| 37 |
|
| 38 |
{ An optional argument. It must be given as @--option=argument |
| 39 |
or (short form) -o=argument. |
| 40 |
|
| 41 |
If you use a short form and you combine many short option names |
| 42 |
into one parameter, then only the last option may have an argument. |
| 43 |
For example @code(-abc=blah) is equivalent to @code(-a -b -c=blah). } |
| 44 |
oaOptional, |
| 45 |
|
| 46 |
{ A required argument. It must be given as for oaOptional, |
| 47 |
but this time the equal sign is not needed (we know anyway that |
| 48 |
following parameter must be an argument). So the following versions |
| 49 |
are possible: |
| 50 |
|
| 51 |
@preformatted( |
| 52 |
--option=argument # long form, as one parameter |
| 53 |
--option argument # long form, as two parameters |
| 54 |
-o=argument # short form, as one parameter |
| 55 |
-o argument # short form, as two parameters |
| 56 |
) } |
| 57 |
oaRequired, |
| 58 |
|
| 59 |
{ We require a specified (more than one) argument. |
| 60 |
All of the arguments must be specified as separate parameters, like |
| 61 |
|
| 62 |
@preformatted( |
| 63 |
--option Argument1 Argument2 |
| 64 |
-o Argument1 Argument2 |
| 65 |
) } |
| 66 |
oaRequired2Separate, |
| 67 |
oaRequired3Separate, |
| 68 |
oaRequired4Separate, |
| 69 |
oaRequired5Separate, |
| 70 |
oaRequired6Separate, |
| 71 |
oaRequired7Separate, |
| 72 |
oaRequired8Separate, |
| 73 |
oaRequired9Separate |
| 74 |
); |
| 75 |
|
| 76 |
TOptionArguments = set of TOptionArgument; |
| 77 |
|
| 78 |
const |
| 79 |
oaRequiredSeparateFirst = oaRequired2Separate; |
| 80 |
oaRequiredSeparateLast = oaRequired9Separate; |
| 81 |
|
| 82 |
RequiredSeparateFirstCount = 2; |
| 83 |
RequiredSeparateLastCount = RequiredSeparateFirstCount |
| 84 |
+ Ord(oaRequiredSeparateLast) - Ord(oaRequiredSeparateFirst); |
| 85 |
|
| 86 |
OptionArgumentsRequiredSeparate: TOptionArguments = |
| 87 |
[oaRequiredSeparateFirst .. oaRequiredSeparateLast]; |
| 88 |
|
| 89 |
type |
| 90 |
TOptionSeparateArgument = oaRequiredSeparateFirst .. oaRequiredSeparateLast; |
| 91 |
TSeparateArgs = array[1..RequiredSeparateLastCount] of string; |
| 92 |
|
| 93 |
const |
| 94 |
EmptySeparateArgs: TSeparateArgs = ('','','', '','','', '','',''); |
| 95 |
|
| 96 |
type |
| 97 |
{ Callback used by TParameters.Parse to notify about new option. |
| 98 |
|
| 99 |
@param(OptionNum The option number in the Options table (zero-based).) |
| 100 |
|
| 101 |
@param(HasArgument Says if you have a single argument in the Argument |
| 102 |
parameter. Always @false when your option has oaNone or |
| 103 |
oaRequiredXSeparate. Always @true when your option has oaRequired. |
| 104 |
For oaOptional, this is how you know if the optional argument was used.) |
| 105 |
|
| 106 |
@param(Argument A single argument for oaRequired or oaOptional, |
| 107 |
only if HasArgument. Otherwise empty string.) |
| 108 |
|
| 109 |
@param(SeparateArgs For options using oaRequiredXSeparate, |
| 110 |
your arguments are here. You get exactly as many argument |
| 111 |
as your oaRequiredXSeparate requested, the rest of SeparateArgs |
| 112 |
is empty strings.) |
| 113 |
|
| 114 |
@param(Data This is the OptionProcData value you passed to TParameters.Parse, |
| 115 |
use this to pass some pointer to your callback.) |
| 116 |
} |
| 117 |
TOptionProc = procedure (OptionNum: Integer; HasArgument: boolean; |
| 118 |
const Argument: string; const SeparateArgs: TSeparateArgs; Data: Pointer); |
| 119 |
|
| 120 |
{ Command-line option specification, for TParameters.Parse. |
| 121 |
|
| 122 |
Both Short and Long option names are case-sensitive. |
| 123 |
The convention is to make Long option names using only lower-case letters, |
| 124 |
separates by dashes, like @code(my-option-name). |
| 125 |
|
| 126 |
Note that spaces are allowed (as Short option name, or within Long |
| 127 |
option nam), but in practice should not be used as they are a pain |
| 128 |
to pass for the users (you'd have to quote option names under most shells). } |
| 129 |
TOption = record |
| 130 |
{ Short option name. Use #0 if none. Cannot be '-' or '=' (these would |
| 131 |
cause ambiguity when parsing options). } |
| 132 |
Short: Char; |
| 133 |
{ Long option name. Use '' if none. Cannot contain '=' (this would |
| 134 |
cause ambiguity when parsing options). } |
| 135 |
Long: string; |
| 136 |
Argument: TOptionArgument; |
| 137 |
end; |
| 138 |
POption = ^TOption; |
| 139 |
|
| 140 |
TOption_Array = array [0..MaxInt div SizeOf(TOption) - 1] of TOption; |
| 141 |
POption_Array = ^TOption_Array; |
| 142 |
|
| 143 |
{ Storing and processing command-line parameters and options. |
| 144 |
For simple processing, you can just read values of this list, |
| 145 |
checking count with comfortable methods like CheckHigh. |
| 146 |
For more involved processing, use the Parse function, |
| 147 |
that does a whole job for you based on a simple specification |
| 148 |
of allowed options. |
| 149 |
|
| 150 |
Some terminology: |
| 151 |
|
| 152 |
@definitionList( |
| 153 |
@itemLabel @italic(Parameter) |
| 154 |
@item(Command-line parameters list is given directly by the OS to our |
| 155 |
program. These are the contents of this list, |
| 156 |
initialized from the standard Pascal ParamStr/ParamCount. |
| 157 |
They can be modified to remove the already-handled parameters.) |
| 158 |
|
| 159 |
@itemLabel @italic(Option) |
| 160 |
@item(Options are things encoded by the user in the parameters. |
| 161 |
Examples: |
| 162 |
|
| 163 |
@unorderedList( |
| 164 |
@item(Command-line |
| 165 |
|
| 166 |
@preformatted( castle-model-viewer --navigation Walk) |
| 167 |
|
| 168 |
passes two parameters (@code(@--navigation) and @code(Walk)) |
| 169 |
for castle-model-viewer, and these two parameters form one option: |
| 170 |
@code(@--navigation=Walk).) |
| 171 |
|
| 172 |
@item(Command-line |
| 173 |
|
| 174 |
@preformatted( castle-model-viewer -hv) |
| 175 |
|
| 176 |
passes one parameter (@code(-hv)) for castle-model-viewer, |
| 177 |
and inside this parameter two options are encoded: |
| 178 |
@code(-h) and @code(-v).) |
| 179 |
) |
| 180 |
|
| 181 |
The very idea of this unit is to decode "options" from the "parameters". |
| 182 |
) |
| 183 |
|
| 184 |
@itemLabel @italic(Argument) |
| 185 |
@item(Argument is a part of the option, that clarifies what this option does. |
| 186 |
For example in @code(@--navigation=Walk), "@code(Walk)" is the argument |
| 187 |
and "@code(@--navigation)" is the option long name. |
| 188 |
|
| 189 |
Some options don't take any arguments, some take optional argument, |
| 190 |
some take required argument, some have a couple of arguments. |
| 191 |
TOptionArgument type allows you to specify all this.) |
| 192 |
) |
| 193 |
|
| 194 |
For simple programs, you can directly parse command-line by looking at |
| 195 |
our parameters strings. For more involved cases, |
| 196 |
using @link(Parse) method has a lot of advantages: |
| 197 |
|
| 198 |
@unorderedList( |
| 199 |
@item(Less error-prone, and your program's code stays simple.) |
| 200 |
|
| 201 |
@item(We automatically handle special parameter @-- that is a standard |
| 202 |
way to mark the end of the options. (Useful for users that have filenames |
| 203 |
that start with "-" character.)) |
| 204 |
|
| 205 |
@item(We automatically detect and make exceptions with nice messages |
| 206 |
on various errors. For example unrecognized options are clearly |
| 207 |
reported (so they will not mistaken for e.g. missing filenames |
| 208 |
by your program).) |
| 209 |
|
| 210 |
@item(We automatically allow combining of short options, |
| 211 |
so user can use @code(-abc) instead of @code(-a -b -c).) |
| 212 |
|
| 213 |
@item(We have a simple interface, where you simply specify what |
| 214 |
options you want, long and short option names, option arguments |
| 215 |
and such.) |
| 216 |
) |
| 217 |
|
| 218 |
See [https://castle-engine.io/common_options.php] |
| 219 |
for a user description how short and long options are expected to be given |
| 220 |
on the command-line. } |
| 221 |
TParameters = class(TCastleStringList) |
| 222 |
public |
| 223 |
function High: Integer; |
| 224 |
|
| 225 |
{ Does the number of parameters (High) satisfy given condition. |
| 226 |
@raises EInvalidParams When High is wrong. |
| 227 |
@groupBegin } |
| 228 |
procedure CheckHigh(ParamValue: integer); |
| 229 |
procedure CheckHighAtLeast(ParamValue: integer); |
| 230 |
procedure CheckHighAtMost(ParamValue: integer); |
| 231 |
{ @groupEnd } |
| 232 |
|
| 233 |
{ Is one of given strings present on the parameters list. |
| 234 |
Looks inside Strings[1..High], case sensitive. } |
| 235 |
function IsPresent(const A: array of string): boolean; |
| 236 |
|
| 237 |
{ Parse command-line parameters. Given a specification of your command-line |
| 238 |
options (in AOptions), we will find and pass these options to your |
| 239 |
OptionProc callback. The handled options will be removed from |
| 240 |
the @link(Parameters) list. |
| 241 |
|
| 242 |
After running this, you should treat the remaining @link(Parameters) |
| 243 |
as "normal" parameters, usually a filenames to open by your program or such. |
| 244 |
|
| 245 |
See also TOption for a specification of an option, |
| 246 |
and see TOptionArgument for a specification of an option argument, |
| 247 |
and see TOptionProc for a specification what your OptionProc callback gets. |
| 248 |
|
| 249 |
@raises EInvalidShortOption On invalid (unknown) short option name. |
| 250 |
@raises EInvalidLongOption On invalid long option name. |
| 251 |
@raises(EExcessiveOptionArgument When an option gets too many arguments, |
| 252 |
this may happen for options with oaNone or oaRequiredXSeparate |
| 253 |
that are specified with @code(--option=argument) form.) |
| 254 |
@raises(EMissingOptionArgument When an option gets too few arguments, |
| 255 |
this may happen when argument for oaRequired option is missing, |
| 256 |
or when too few arguments are given for oaRequiredXSeparate option.) |
| 257 |
@raises(EInvalidParams On invalid parameter without an option, |
| 258 |
like @code(-=argument) or @code(--=argument).) |
| 259 |
|
| 260 |
Note that a single dash parameter is left alone, without making any |
| 261 |
exceptions, as this is a standard way of telling "standard input" |
| 262 |
or "standard output" for some programs. |
| 263 |
|
| 264 |
Note that a double dash parameter @-- is handled and removed from |
| 265 |
the @link(Parameters) list, and signals an end of options. |
| 266 |
|
| 267 |
You should not modify @link(Parameters) list when this function |
| 268 |
is running, in particular do not modify it from your OptionProc callback. |
| 269 |
Also, do not depend on when the handled options are exactly removed |
| 270 |
from the @link(Parameters) list (before or after OptionProc callback). |
| 271 |
|
| 272 |
We never touch here the Strings[0] value, we look |
| 273 |
only at the Strings[1] to Strings[High]. |
| 274 |
|
| 275 |
ParseOnlyKnownOptions = @true makes this procedure work a little |
| 276 |
differently, it's designed to allow you to process @italic(some) options |
| 277 |
and leave the rest options not handled (without making any error): |
| 278 |
|
| 279 |
@orderedList( |
| 280 |
@item(The "known" short options (in Options param) are recognized |
| 281 |
only if they are not combined with other options. |
| 282 |
E.g. if you allow '-c' in Options, we will handle '-c' parameter, |
| 283 |
but 'c' will be ignored in combined '-abc' parameter.) |
| 284 |
@item(All unknown short and long options are ignored, without making any error.) |
| 285 |
@item(The special @-- is handled (signals the end of options), |
| 286 |
but it's not removed from the @link(Parameters).) |
| 287 |
) |
| 288 |
|
| 289 |
The ParseOnlyKnownOptions = @true is useful if you want to handle |
| 290 |
some command-line options, but you still want to leave final options |
| 291 |
parsing to a later code. For example TCastleWindow.ParseParameters parses |
| 292 |
some window parameters (like --geometry), leaving your program-specific |
| 293 |
stuff in peace. |
| 294 |
|
| 295 |
Note that ParseOnlyKnownOptions = @true isn't an absolutely |
| 296 |
fool-proof solution, for example the command-line |
| 297 |
@code(castle-model-viewer --navigation --geometry 800x600 Walk) is actually invalid. |
| 298 |
But we will handle it, by first detecting and removing @code(--geometry 800x600) |
| 299 |
from TCastleWindow.ParseParameters, and then detecting and removing |
| 300 |
@code(--navigation Walk) from castle-model-viewer code. |
| 301 |
Basically, processing by Parse many times is not fool-proof |
| 302 |
in some weird situations. |
| 303 |
|
| 304 |
@groupBegin } |
| 305 |
procedure Parse(const AOptions: POption_Array; const OptionsCount: Integer; |
| 306 |
const OptionProc: TOptionProc; const OptionProcData: Pointer; |
| 307 |
const ParseOnlyKnownOptions: boolean = false); overload; |
| 308 |
procedure Parse(const AOptions: array of TOption; |
| 309 |
const OptionProc: TOptionProc; const OptionProcData: Pointer; |
| 310 |
const ParseOnlyKnownOptions: boolean = false); overload; |
| 311 |
{ @groupEnd } |
| 312 |
end; |
| 313 |
|
| 314 |
function SeparateArgsToVector3(const v: TSeparateArgs): TVector3; |
| 315 |
function SeparateArgsToVector3Single(const v: TSeparateArgs): TVector3; |
| 316 |
deprecated 'use SeparateArgsToVector3'; |
| 317 |
|
| 318 |
const |
| 319 |
OnlyHelpOptions: array [0..0] of TOption = ( |
| 320 |
(Short: 'h'; Long: 'help'; Argument: oaNone) |
| 321 |
) deprecated 'define this in your application'; |
| 322 |
|
| 323 |
HelpOptionHelp = |
| 324 |
' -h / --help Print this help message and exit.' |
| 325 |
deprecated 'use OptionDescription'; |
| 326 |
VersionOptionHelp = |
| 327 |
' -v / --version Print the version number and exit.' |
| 328 |
deprecated 'use OptionDescription'; |
| 329 |
|
| 330 |
var |
| 331 |
{ Command-line parameters. Initialized from standard |
| 332 |
ParamStr(0) ... ParamStr(ParamCount). Can be later modified, |
| 333 |
which is good --- you can remove handled parameters. |
| 334 |
You also have all the methods of TCastleStringList class |
| 335 |
(e.g. you can assign to another TCastleStringList instance). } |
| 336 |
Parameters: TParameters; |
| 337 |
|
| 338 |
{ Return a multiline command-line option help, |
| 339 |
containing the option name and description, |
| 340 |
nicely indented and broken into multiple lines. |
| 341 |
Existing newlines in Description are correctly accounted for. } |
| 342 |
function OptionDescription(const Name, Description: string): string; |
| 343 |
|
| 344 |
implementation |
| 345 |
|
| 346 |
function OptionSeparateArgumentToCount(const v: TOptionSeparateArgument): Integer; forward; |
| 347 |
|
| 348 |
{ TParameters ---------------------------------------------------------------- } |
| 349 |
|
| 350 |
function ParametersCountString(Count: Integer; const MiddleStr: string): string; overload; |
| 351 |
begin |
| 352 |
result := IntToStr(Count); |
| 353 |
if Count = 1 then |
| 354 |
result := result +MiddleStr +' parameter' |
| 355 |
else |
| 356 |
result := result +MiddleStr +' parameters'; |
| 357 |
end; |
| 358 |
|
| 359 |
function ParametersCountString(Count: Integer): string; overload; |
| 360 |
begin |
| 361 |
result := ParametersCountString(Count, ''); |
| 362 |
end; |
| 363 |
|
| 364 |
{ Since we can modify Parameters, we can't really output |
| 365 |
in CheckHigh* for user how many parameters were excepted (because you maybe |
| 366 |
ate some). Output only how many params are missing/too much. } |
| 367 |
|
| 368 |
function TParameters.High: Integer; |
| 369 |
begin |
| 370 |
Result := Count - 1; |
| 371 |
end; |
| 372 |
|
| 373 |
procedure TParameters.CheckHigh(ParamValue: integer); |
| 374 |
begin |
| 375 |
if ParamValue <> High then |
| 376 |
begin |
| 377 |
if ParamValue < High then |
| 378 |
raise EInvalidParams.Create('Expected ' + |
| 379 |
ParametersCountString(High-ParamValue, ' less')) else |
| 380 |
raise EInvalidParams.Create('Expected ' + |
| 381 |
ParametersCountString(ParamValue-High, ' more')); |
| 382 |
end; |
| 383 |
end; |
| 384 |
|
| 385 |
procedure TParameters.CheckHighAtLeast(ParamValue: integer); |
| 386 |
begin |
| 387 |
if ParamValue > High then |
| 388 |
raise EInvalidParams.Create('Expected ' + |
| 389 |
ParametersCountString(ParamValue-High, ' more')); |
| 390 |
end; |
| 391 |
|
| 392 |
procedure TParameters.CheckHighAtMost(ParamValue: integer); |
| 393 |
begin |
| 394 |
if ParamValue < High then |
| 395 |
raise EInvalidParams.Create('Expected ' + |
| 396 |
ParametersCountString(High-ParamValue, ' less')); |
| 397 |
end; |
| 398 |
|
| 399 |
function TParameters.IsPresent(const A: array of string): boolean; |
| 400 |
var |
| 401 |
I, J: Integer; |
| 402 |
begin |
| 403 |
for I := 1 to High do |
| 404 |
for J := 0 to System.High(A) do |
| 405 |
if Strings[I] = A[J] then |
| 406 |
Exit(true); |
| 407 |
Result := false; |
| 408 |
end; |
| 409 |
|
| 410 |
procedure TParameters.Parse(const AOptions: array of TOption; const OptionProc: TOptionProc; |
| 411 |
const OptionProcData: Pointer; const ParseOnlyKnownOptions: boolean); |
| 412 |
begin |
| 413 |
Parse(@AOptions, System.High(AOptions) + 1, OptionProc, OptionProcData, |
| 414 |
ParseOnlyKnownOptions); |
| 415 |
end; |
| 416 |
|
| 417 |
procedure TParameters.Parse( |
| 418 |
const AOptions: POption_Array; const OptionsCount: Integer; const OptionProc: TOptionProc; |
| 419 |
const OptionProcData: Pointer; const ParseOnlyKnownOptions: boolean); |
| 420 |
|
| 421 |
{ Splits S into |
| 422 |
|
| 423 |
- rejected prefix, which is either "-" or "--" depending on PrefixLength = 1 or 2 |
| 424 |
- ParamName, which is the part before "=" (or everything, if parameter has no "="), |
| 425 |
and it cannot be empty otherwise we raise exception |
| 426 |
- Argument, which is the part after "=" (or nothing, if parameter has no "=") |
| 427 |
|
| 428 |
Examples: |
| 429 |
|
| 430 |
SplitParameter('-', ..., 1) -> exception (empty ParamName) |
| 431 |
SplitParameter('--', ..., 2) -> exception (empty ParamName) |
| 432 |
SplitParameter('--=file.txt', ..., 2) -> exception (empty ParamName) |
| 433 |
SplitParameter('-=file.txt', ..., 1) -> exception (empty ParamName) |
| 434 |
SplitParameter('-f=file.txt', ..., 1) -> |
| 435 |
ParamName = 'f' |
| 436 |
HasArgument = true |
| 437 |
Argument = 'file.txt' |
| 438 |
SplitParameter('--read-file=file.txt', ..., 2) -> |
| 439 |
ParamName = 'read-file' |
| 440 |
HasArgument = true |
| 441 |
Argument = 'file.txt' |
| 442 |
SplitParameter('-xzvf=file.txt', ..., 2) -> |
| 443 |
ParamName = 'xzvf' // called must interpret it as a series of short options |
| 444 |
HasArgument = true |
| 445 |
Argument = 'file.txt' |
| 446 |
} |
| 447 |
procedure SplitParameter(const S: string; out ParamName: string; |
| 448 |
out HasArgument: boolean; out Argument: string; const PrefixLength: Integer); |
| 449 |
var |
| 450 |
p: Integer; |
| 451 |
begin |
| 452 |
p := Pos('=', s); |
| 453 |
HasArgument := p <> 0; |
| 454 |
if HasArgument then |
| 455 |
begin |
| 456 |
ParamName := CopyPos(s, PrefixLength + 1, p - 1); |
| 457 |
Argument := SEnding(s, p+1); |
| 458 |
end else |
| 459 |
begin |
| 460 |
ParamName := SEnding(s, PrefixLength + 1); |
| 461 |
Argument := ''; |
| 462 |
end; |
| 463 |
|
| 464 |
if ParamName = '' then |
| 465 |
raise EInvalidParams.Create('Invalid empty parameter "' + s + '"'); |
| 466 |
end; |
| 467 |
|
| 468 |
{ s jest jakims parametrem ktory zaczyna sie od '--' i nie jest rowny '--'. |
| 469 |
Wyciaga z s-a opcje jaka reprezentuje (i zwraca jej numer w Params, |
| 470 |
zero-based), wyciaga tez zapisany razem z nia parametr i zwraca |
| 471 |
HasArgument i Argument (pamietaj ze wyciaga tylko argumenty dolaczone |
| 472 |
do opcji przy pomocy znaku "="; nie sprawdza tez w ogole czy HasArgument |
| 473 |
w jakis sposob zgadza sie z Options[result].Argument.). |
| 474 |
|
| 475 |
Jezeli ParseOnlyKnownOptions to moze zwrocic -1 aby zaznaczyc ze |
| 476 |
ten parametr nie reprezentuje zadnej znanej opcji (chociaz ciagle |
| 477 |
nieprawidlowe postacie w rodzaju --=argument czy --non-arg-option=argument |
| 478 |
beda oczywiscie powodowaly wyjatek.) } |
| 479 |
function ParseLongParameter(const s: string; out HasArgument: boolean; |
| 480 |
out Argument: string): Integer; |
| 481 |
var |
| 482 |
ParamLong: string; |
| 483 |
i: Integer; |
| 484 |
begin |
| 485 |
SplitParameter(s, ParamLong, HasArgument, Argument, 2); |
| 486 |
for i := 0 to OptionsCount-1 do |
| 487 |
if AOptions^[i].Long = ParamLong then |
| 488 |
begin result := i; Exit; end; |
| 489 |
|
| 490 |
if ParseOnlyKnownOptions then |
| 491 |
result := -1 |
| 492 |
else |
| 493 |
raise EInvalidLongOption.Create('Invalid long option "'+s+'"'); |
| 494 |
end; |
| 495 |
|
| 496 |
{ Find index of option with AOptions[I].Short = C (also check that C <> #0). |
| 497 |
|
| 498 |
If fails -- EInvalidshortOption (if ParseOnlyKnownOptions = false) |
| 499 |
or exits with -1 (if ParseOnlyKnownOptions). |
| 500 |
|
| 501 |
Note that "Parameter" is useful only to construct nice error message, |
| 502 |
it should be parameter where we found C. } |
| 503 |
function FindShortOption(const c: char; const Parameter: string): Integer; |
| 504 |
const |
| 505 |
SInvalidShortOpt = 'Invalid short option character "%s" in parameter "%s"'; |
| 506 |
begin |
| 507 |
if c = #0 then |
| 508 |
begin |
| 509 |
if ParseOnlyKnownOptions then |
| 510 |
Exit(-1) |
| 511 |
else |
| 512 |
raise EInvalidShortOption.CreateFmt(SInvalidShortOpt, ['#0 (null char)', Parameter]); |
| 513 |
end; |
| 514 |
|
| 515 |
for result := 0 to OptionsCount-1 do |
| 516 |
if AOptions^[result].Short = c then |
| 517 |
Exit; |
| 518 |
|
| 519 |
if ParseOnlyKnownOptions then |
| 520 |
Exit(-1) |
| 521 |
else |
| 522 |
raise EInvalidShortOption.CreateFmt(SInvalidShortOpt, [c, Parameter]); |
| 523 |
end; |
| 524 |
|
| 525 |
{ s jest jakims parametrem zaczynajacym sie od '-' i nie bedacym '-'. |
| 526 |
Dziala tak jak ParseLongParameter... |
| 527 |
|
| 528 |
- ponadto do SimpleShortOptions dopisze ciag prostych opcji ktore zostaly |
| 529 |
podane razem z ostatnia opcja (czyli z opcja zwracana pod nazwa). |
| 530 |
Te proste opcje zostaly "skombinowane" razem z ostatnia opcja w |
| 531 |
jednym parametrze. W rezultacie nazywam je "prostymi" bo one nie moga |
| 532 |
miec argumentu - AOptions^[].Argument tych opcji moze byc tylko oaNone |
| 533 |
lub oaOptional. Ta procedura NIE sprawdza ze to sie zgadza |
| 534 |
tak jak w ogole nie sprawdza zadnego AOptions^[].Argument, takze |
| 535 |
dla ostatniej (zwracanej pod nazwa) opcji nie sprawdza - moze wiec |
| 536 |
zwrocic opcje oaNone z HasArgument albo oaRequired[*Separate] z |
| 537 |
not HasArgument. |
| 538 |
|
| 539 |
Ten kto uzywa tej opcji musi sprawdzic czy HasArgument ma sens ze |
| 540 |
zwrocona opcja. W przypadku oaRequired[*Separate] moze/musi odczytac |
| 541 |
dalsze parametry zeby postac argument/argumenty opcji. |
| 542 |
Zasada jest taka ze ta procedura zajmuje sie TYLKO parametrem s. |
| 543 |
Ona nie wchodzi na inne Strings[], zreszta w ogole nie wie dla jakiego |
| 544 |
I zachodzi Strings[I] = s. |
| 545 |
} |
| 546 |
function ParseShortParameter(const s: string; out HasArgument: boolean; |
| 547 |
out Argument: string; const SimpleShortOptions: TIntegerList): Integer; |
| 548 |
var |
| 549 |
ParamAllShortOptions: string; |
| 550 |
OptionIndex: Integer; |
| 551 |
i: Integer; |
| 552 |
begin |
| 553 |
{ calculate ParamAllShortOptions, HasArgument, Argument } |
| 554 |
SplitParameter(s, ParamAllShortOptions, HasArgument, Argument, 1); |
| 555 |
|
| 556 |
{ When ParseOnlyKnownOptions we ignore combined short options, like '-abc', |
| 557 |
even if one of them (like 'c') is known. |
| 558 |
It would be complicated to remove only known options. } |
| 559 |
if ParseOnlyKnownOptions and (Length(ParamAllShortOptions) > 1) then |
| 560 |
Exit(-1); |
| 561 |
|
| 562 |
{ add to SimpleShortOptions } |
| 563 |
for i := 1 to Length(ParamAllShortOptions) - 1 do |
| 564 |
begin |
| 565 |
OptionIndex := FindShortOption(ParamAllShortOptions[i], s); |
| 566 |
{ we are here only if Length(ParamAllShortOptions) > 1, |
| 567 |
so ParseOnlyKnownOptions is false, |
| 568 |
so FindShortOption always answers with something <> -1. } |
| 569 |
Assert(OptionIndex <> -1); |
| 570 |
SimpleShortOptions.Add(OptionIndex); |
| 571 |
end; |
| 572 |
|
| 573 |
{ handle last short option in ParamAllShortOptions } |
| 574 |
OptionIndex := FindShortOption(ParamAllShortOptions[Length(ParamAllShortOptions)], s); |
| 575 |
{ OptionIndex may be -1 here, |
| 576 |
if ParseOnlyKnownOptions = true and FindShortOption returned -1, |
| 577 |
and then we just want to return -1. } |
| 578 |
Result := OptionIndex; |
| 579 |
end; |
| 580 |
|
| 581 |
var |
| 582 |
i, j, k, OptionNum: Integer; |
| 583 |
HasArgument: boolean; |
| 584 |
Argument, OptionName: string; |
| 585 |
SeparateArgs: TSeparateArgs; |
| 586 |
SimpleShortOptions: TIntegerList; |
| 587 |
begin |
| 588 |
i := 1; |
| 589 |
SimpleShortOptions := TIntegerList.Create; |
| 590 |
try |
| 591 |
|
| 592 |
while i <= High do |
| 593 |
begin |
| 594 |
if Strings[i] = '--' then |
| 595 |
begin |
| 596 |
if not ParseOnlyKnownOptions then Delete(I); |
| 597 |
Break; |
| 598 |
end; |
| 599 |
|
| 600 |
Assert(SimpleShortOptions.Count = 0); |
| 601 |
|
| 602 |
{ calculate OptionNum: |
| 603 |
|
| 604 |
- -1 if Strings[I] is not recognized as a valid option. |
| 605 |
|
| 606 |
This can happen only if ParseOnlyKnownOptions (otherwise invalid |
| 607 |
option will cause exception from ParseShortParameter, ParseLongParameter) |
| 608 |
|
| 609 |
- or an index in Params, if Strings[I] is a valid option. |
| 610 |
In this case also OptionName is set. |
| 611 |
In this case also SimpleShortOptions is relevant, |
| 612 |
which are combined short options present before the option indicated by OptionNum. |
| 613 |
|
| 614 |
E.g. "-abc=file.txt", assuming that all "a" "b" "c" are valid short options, |
| 615 |
means that "a", "b" are in SimpleShortOptions, |
| 616 |
and "c" is indicated by OptionNum and OptionName. |
| 617 |
|
| 618 |
Note about "Length(Strings[i]) > 1" condition: |
| 619 |
it means that "-" is treated as non-special parameter (it is commonly used |
| 620 |
as stdin / stdout name), instead of making an exception about invalid short option. } |
| 621 |
|
| 622 |
OptionNum := -1; |
| 623 |
if SCharIs(Strings[i], 1, '-') and (Length(Strings[i]) > 1) then |
| 624 |
begin |
| 625 |
if SCharIs(Strings[i], 2, '-') then |
| 626 |
begin |
| 627 |
OptionNum := ParseLongParameter(Strings[i], HasArgument, Argument); |
| 628 |
if OptionNum <> -1 then OptionName := '--'+AOptions^[OptionNum].Long; |
| 629 |
end else |
| 630 |
begin |
| 631 |
OptionNum := ParseShortParameter(Strings[i], HasArgument, Argument, SimpleShortOptions); |
| 632 |
if OptionNum <> -1 then OptionName := '-'+AOptions^[OptionNum].Short; |
| 633 |
end; |
| 634 |
end; |
| 635 |
|
| 636 |
if OptionNum <> -1 then |
| 637 |
begin |
| 638 |
{ first handle SimpleShortOptions } |
| 639 |
for k := 0 to SimpleShortOptions.Count-1 do |
| 640 |
begin |
| 641 |
if not (AOptions^[SimpleShortOptions[k]].Argument in [oaNone, oaOptional]) then |
| 642 |
raise EMissingOptionArgument.Create('Missing argument for short option -'+ |
| 643 |
AOptions^[SimpleShortOptions[k]].Short +'; when combining short options only the last '+ |
| 644 |
'option can have an argument'); |
| 645 |
OptionProc(SimpleShortOptions[k], false, '', EmptySeparateArgs, OptionProcData); |
| 646 |
end; |
| 647 |
SimpleShortOptions.Count := 0; |
| 648 |
|
| 649 |
{ now handle OptionNum and OptionName } |
| 650 |
|
| 651 |
Delete(I); |
| 652 |
SeparateArgs := EmptySeparateArgs; |
| 653 |
|
| 654 |
{ upewnij sie ze HasArgument ma dopuszczalna wartosc. Odczytaj argumenty |
| 655 |
podane jako osobne paranetry dla oaRequired i oaRequired?Separate. } |
| 656 |
|
| 657 |
if (AOptions^[OptionNum].Argument = oaRequired) and (not HasArgument) then |
| 658 |
begin |
| 659 |
if i > High then |
| 660 |
raise EMissingOptionArgument.Create('Missing argument for option '+OptionName); |
| 661 |
HasArgument := true; |
| 662 |
Argument := Strings[i]; |
| 663 |
Delete(i); |
| 664 |
end else |
| 665 |
if (AOptions^[OptionNum].Argument = oaNone) and HasArgument then |
| 666 |
begin |
| 667 |
raise EExcessiveOptionArgument.Create('Excessive argument for option '+OptionName); |
| 668 |
end else |
| 669 |
if AOptions^[OptionNum].Argument in OptionArgumentsRequiredSeparate then |
| 670 |
begin |
| 671 |
if HasArgument then |
| 672 |
raise EExcessiveOptionArgument.CreateFmt('Option %s requires %d arguments, '+ |
| 673 |
'you cannot give them using the form --option=argument, you must give '+ |
| 674 |
'all the arguments as separate parameters', [OptionName, |
| 675 |
OptionSeparateArgumentToCount(AOptions^[OptionNum].Argument) ]); |
| 676 |
|
| 677 |
for j := 1 to OptionSeparateArgumentToCount(AOptions^[OptionNum].Argument) do |
| 678 |
begin |
| 679 |
if i > High then |
| 680 |
raise EMissingOptionArgument.CreateFmt('Not enough arguments for option %s, '+ |
| 681 |
'this option needs %d arguments but we have only %d', [OptionName, |
| 682 |
OptionSeparateArgumentToCount(AOptions^[OptionNum].Argument), j-1]); |
| 683 |
SeparateArgs[j] := Strings[i]; |
| 684 |
Delete(i); |
| 685 |
end; |
| 686 |
end; |
| 687 |
|
| 688 |
OptionProc(OptionNum, HasArgument, Argument, SeparateArgs, OptionProcData); |
| 689 |
end else |
| 690 |
Inc(i); |
| 691 |
end; |
| 692 |
|
| 693 |
finally FreeAndNil(SimpleShortOptions) end; |
| 694 |
end; |
| 695 |
|
| 696 |
{ some simple helper utilities ---------------------------------------------- } |
| 697 |
|
| 698 |
function OptionSeparateArgumentToCount(const v: TOptionSeparateArgument): Integer; |
| 699 |
begin |
| 700 |
Result := RequiredSeparateFirstCount + Ord(v) - Ord(oaRequiredSeparateFirst) |
| 701 |
end; |
| 702 |
|
| 703 |
function SeparateArgsToVector3(const v: TSeparateArgs): TVector3; |
| 704 |
begin |
| 705 |
Result.X := StrToFloatDot(v[1]); |
| 706 |
Result.Y := StrToFloatDot(v[2]); |
| 707 |
Result.Z := StrToFloatDot(v[3]); |
| 708 |
end; |
| 709 |
|
| 710 |
function SeparateArgsToVector3Single(const v: TSeparateArgs): TVector3; |
| 711 |
begin |
| 712 |
Result := SeparateArgsToVector3(V); |
| 713 |
end; |
| 714 |
|
| 715 |
procedure InitializationParams; |
| 716 |
var |
| 717 |
I: Integer; |
| 718 |
begin |
| 719 |
Parameters := TParameters.Create; |
| 720 |
for I := 0 to ParamCount do |
| 721 |
Parameters.Add(ParamStr(i)); |
| 722 |
end; |
| 723 |
|
| 724 |
procedure FinalizationParams; |
| 725 |
begin |
| 726 |
FreeAndNil(Parameters); |
| 727 |
end; |
| 728 |
|
| 729 |
function OptionDescription(const Name, Description: string): string; |
| 730 |
const |
| 731 |
MaxLineWidth = 75; |
| 732 |
Indent = 24; |
| 733 |
NameIndent = 2; |
| 734 |
var |
| 735 |
PadLength: Integer; |
| 736 |
begin |
| 737 |
Result := StringOfChar(' ', NameIndent) + Name; |
| 738 |
PadLength := Indent - Length(Result); |
| 739 |
if PadLength > 0 then |
| 740 |
{ option name and first line of description can fit on a single line } |
| 741 |
Result := Result + StringOfChar(' ', PadLength) |
| 742 |
else |
| 743 |
Result := Result + NL + StringOfChar(' ', Indent); |
| 744 |
|
| 745 |
Result := Result + BreakLine(Description, MaxLineWidth - Indent, WhiteSpaces, |
| 746 |
NL, StringOfChar(' ', Indent)); |
| 747 |
end; |
| 748 |
|
| 749 |
initialization |
| 750 |
InitializationParams; |
| 751 |
finalization |
| 752 |
FinalizationParams; |
| 753 |
end. |