getopt.net
A port of getopt in pure C#.
Loading...
Searching...
No Matches
getopt.net.GetOpt Class Reference

GetOpt-like class for handling getopt-like command-line arguments in .net. More...

Public Member Functions

 GetOpt ()
 Default constructor; it is recommended to use this constructor and to use brace-initialiser-lists to instantiate/configure each instance of this object.
 
 GetOpt (string[] appArgs, string shortOpts, params Option[] options)
 Specialised constructor.
 
int GetNextOpt (out string? outOptArg)
 Gets the next option in the list.
 
CommandOption GetNextOpt ()
 Gets the next option in the list, returning an object containing more detailled information about the option.
 

Static Public Attributes

const char MissingArgChar = '?'
 The character that is returned when an option is missing a required argument.
 
const char InvalidOptChar = '!'
 The character that is returned when an invalid option is returned.
 
const char NonOptChar = (char)1
 The character that is returned when a non-option value is encountered and it is not the argument to an option.
 
const string DoubleDash = "--"
 This is the string getopt.net looks for when DoubleDashStopsParsing is enabled.
 
const char SingleDash = '-'
 A single dash character. This is the character that is searched for, when parsing POSIX-/GNU-like options.
 
const char SingleSlash = '/'
 A single slash. This is the char that is searched for when parsing arguments with the Windows convention.
 
const char WinArgSeparator = ':'
 The argument separator used by Windows.
 
const char GnuArgSeparator = '='
 The argument separator used by POSIX / GNU getopt.
 
const string ArgSplitRegex = @"([\s]|[=])"
 The regex used by ArgumentSplitter to split arguments into a key-value pair.
 
const char SingleAtSymbol = '@'
 A single "at" character. This character is used when AllowParamFiles is enabled, to determine whether or not a param file has been passed to getopt.net.
 

Protected Member Functions

void ResetOptPosition ()
 Resets the option position to 1.
 
bool MustReturnChar1 ()
 Gets a value indicating whether or not non-options should be handled as if they were the argument of an option with the character code 1.
 
bool MustStopParsing ()
 If the first character of ShortOpts is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered.
 
int ParseLongOption (out string? optArg)
 Parses long options.
 
bool TryGetArgumentForShortOption (ref string? arg, out bool incrementCurrentIndex)
 Attempts to retrieve the argument for the current short option.
 
int ParseShortOption (out string? optArg)
 Parses a single short option.
 
ArgumentTypeShortOptRequiresArg (char shortOpt)
 Gets a value indicating whether or not a short option requires an argument.
 
bool HasArgumentInOption (out string optName, out string? argVal)
 Determines whether or not the current option contains its argument with the string or not.
 
string StripDashes (bool isLongOpt)
 Strips leading dashes from strings.
 
bool IsLongOption (string arg)
 Gets a value indicating whether or not the current string is a long option.
 
bool IsShortOption (string arg)
 Gets a value indicating whether or not the current string is/contains a (or more) short option.
 
bool IsParamFileArg (string arg, out string? paramFile)
 Gets a value indicating whether or not a given option is a paramfile option. AllowParamFiles.
 
void ReadParamFile (FileInfo paramFile)
 Reads the incoming param file and adds the contents to AppArgs
 

Static Protected Member Functions

static Regex ArgumentSplitter ()
 Compiled Regex.
 
static bool ShallStopParsing (ref string arg)
 Gets a value indicating whether or not the parser shall stop here.
 

Protected Attributes

int m_currentIndex = 0
 The current index while traversing AppArgs
 
int m_optPosition = 1
 The current position in a multi-option string such as "-xvzRf" when parsing short options.
 

Properties

Option[] Options = Array.Empty<Option>() [get, set]
 An optional list of long options to go with the short options.
 
string? ShortOpts = null [get, set]
 The short opts to use.
 
bool DoubleDashStopsParsing = true [get, set]
 Gets or sets a value indicating whether or not "--" stops parsing. Default:
 
string[] AppArgs [get, set]
 Gets or sets the arguments to parse.
 
bool OnlyShortOpts = false [get, set]
 Gets or sets a value indicating whether or not to only parse short options. Default:
 
bool IgnoreEmptyOptions = true [get, set]
 Gets or sets a value indicating whether or not to ignore empty values. Default:
 
bool IgnoreMissingArgument = false [get, set]
 Gets or sets a value indicating whether or not to ignore missing arguments. Default:
 
bool IgnoreInvalidOptions = true [get, set]
 Gets or sets a value indicating whether or not invalid arguments should be ignored or not. Default:
 
bool IgnoreEmptyAppArgs = true [get, set]
 Gets or sets a value indicating whether or not empty AppArgs are ignored or throw an exception. Default:
 
bool StopParsingOptions = false [get, set]
 Gets or sets a value indicating whether or not option parsing shall stop or not. Default:
 
bool AllowWindowsConventions = false [get, set]
 Gets or sets a value indicating whether or not Windows argument conventions are allowed. Default:
 
bool AllowPowershellConventions = false [get, set]
 Gets or sets a value indicating whether or not Powershell-style arguments are allowed. This option doesn't conflict with the GNU/POSIX or Windows-style argument parsing and is simply an addition.
 
bool AllowParamFiles = false [get, set]
 Gets or sets a value indicating whether or not parameter files are accepted as a valid form of input.
 
bool AllExceptionsDisabled [get, set]
 Either enables or disabled exceptions entirely. For more specific control over exceptions, see the other options provided by GetOpt.
 
int CurrentIndex [get]
 Gets the current index of the app arguments being parsed.
 

Private Attributes

string[] m_appArgs = Array.Empty<string>()
 

Detailed Description

GetOpt-like class for handling getopt-like command-line arguments in .net.

This class contains all the properties and logic required for parsing getopt-like command-line arguments.

A detailled description of the usage of this class can be found in the .

Definition at line 15 of file GetOpt.cs.

Constructor & Destructor Documentation

◆ GetOpt() [1/2]

getopt.net.GetOpt.GetOpt ( )
inline

Default constructor; it is recommended to use this constructor and to use brace-initialiser-lists to instantiate/configure each instance of this object.

Definition at line 201 of file GetOpt.cs.

201{ }

◆ GetOpt() [2/2]

getopt.net.GetOpt.GetOpt ( string[]  appArgs,
string  shortOpts,
params Option[]  options 
)
inline

Specialised constructor.

Parameters
appArgsThe arguments passed to the application.
shortOpts
options

Definition at line 209 of file GetOpt.cs.

209 {
210 AppArgs = appArgs;
211 ShortOpts = shortOpts;
212 Options = options;
213 }
Option[] Options
An optional list of long options to go with the short options.
Definition GetOpt.cs:73
string[] AppArgs
Gets or sets the arguments to parse.
Definition GetOpt.cs:91
string? ShortOpts
The short opts to use.
Definition GetOpt.cs:78

References getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.Options, and getopt.net.GetOpt.ShortOpts.

Member Function Documentation

◆ ArgumentSplitter()

static Regex getopt.net.GetOpt.ArgumentSplitter ( )
staticprotected

Compiled Regex.

Returns
A pre-compiled and optimised regular expression object.

Referenced by getopt.net.GetOpt.HasArgumentInOption().

◆ GetNextOpt() [1/2]

CommandOption getopt.net.GetOpt.GetNextOpt ( )
inline

Gets the next option in the list, returning an object containing more detailled information about the option.

Returns
An instance of CommandOption containing more detailled information about the option and argument (if applicable).

Definition at line 333 of file GetOpt.cs.

333 {
334 var optChar = GetNextOpt(out var optArg);
335
336 if (optArg is null) {
337 return new CommandOption(optChar);
338 }
339
340 if (bool.TryParse(optArg, out bool outBool)) {
341 return new CommandOption(optChar, outBool);
342 } else if (double.TryParse(optArg, out double outDouble)) {
343 return new CommandOption(optChar, outDouble);
344 } else if (float.TryParse(optArg, out float outFloat)) {
345 return new CommandOption(optChar, outFloat);
346 } else if (int.TryParse(optArg, out int outInt)) {
347 return new CommandOption(optChar, outInt);
348 }
349
350 return new CommandOption(optChar, optArg);
351 }
CommandOption GetNextOpt()
Gets the next option in the list, returning an object containing more detailled information about the...
Definition GetOpt.cs:333

References getopt.net.GetOpt.GetNextOpt().

Referenced by getopt.net.GetOpt.GetNextOpt(), and getopt.net.GetOpt.GetNextOpt().

◆ GetNextOpt() [2/2]

int getopt.net.GetOpt.GetNextOpt ( out string?  outOptArg)
inline

Gets the next option in the list.

Parameters
outOptArgOut var; the argument for the option (if applicable).
Returns
The next option.
Exceptions
ParseExceptionIf ignoring errors is disabled (default) and an error occurs.

Definition at line 271 of file GetOpt.cs.

271 {
272 if (AppArgs.Length == 0) {
273 if (!IgnoreEmptyAppArgs) {
274 throw new ParseException("No arguments found for parsing!");
275 } else {
276 outOptArg = null;
277 return -1;
278 }
279 }
280
281 outOptArg = null; // pre-set this here so we don't have to set it during every condition
282
283 if (CurrentIndex >= AppArgs.Length) { return -1; }
284
285 if (string.IsNullOrEmpty(AppArgs[m_currentIndex])) {
286 if (!IgnoreEmptyOptions) {
287 throw new ParseException("Encountered null or empty argument!");
288 } else { return -1; }
289 } else if (DoubleDashStopsParsing && AppArgs[CurrentIndex].Equals(DoubleDash, StringComparison.InvariantCultureIgnoreCase)) {
291 StopParsingOptions = true;
292 return GetNextOpt(out outOptArg);
293 }
294
295 // Check here if StopParsingOptions is true
296 // if so, then simply return NonOptChar and set outOptArg to the value of the argument
297 if (StopParsingOptions) {
298 outOptArg = AppArgs[CurrentIndex];
300 return NonOptChar;
301 }
302
303 // Now check if the current argument is a paramfile argument
304 if (IsParamFileArg(AppArgs[CurrentIndex], out var paramFile) && paramFile is not null) {
305 ReadParamFile(new FileInfo(paramFile));
307 return GetNextOpt(out outOptArg); // We don't need to pass this back to the application. Instead just continue on
308 }
309
311 if (Options.Length == 0) { throw new ParseException("Cannot parse long option! No option list provided!"); }
312 return ParseLongOption(out outOptArg);
313 } else if (IsShortOption(AppArgs[CurrentIndex])) {
314 // check if both arg lists are empty
315 if (string.IsNullOrEmpty(ShortOpts) && Options.Length == 0) { throw new ParseException("Cannot parse short option! No option list provided!"); }
316 return ParseShortOption(out outOptArg);
317 }
318
320 outOptArg = AppArgs[CurrentIndex];
322 if (MustReturnChar1()) { return NonOptChar; }
323 else { return InvalidOptChar; }
324 } else {
325 throw new ParseException(AppArgs[CurrentIndex], "Unexpected option argument!");
326 }
327 }
bool IsParamFileArg(string arg, out string? paramFile)
Gets a value indicating whether or not a given option is a paramfile option. AllowParamFiles.
Definition GetOpt.cs:696
bool IsShortOption(string arg)
Gets a value indicating whether or not the current string is/contains a (or more) short option.
Definition GetOpt.cs:670
bool DoubleDashStopsParsing
Gets or sets a value indicating whether or not "--" stops parsing. Default:
Definition GetOpt.cs:84
void ReadParamFile(FileInfo paramFile)
Reads the incoming param file and adds the contents to AppArgs
Definition GetOpt.cs:715
bool IgnoreEmptyOptions
Gets or sets a value indicating whether or not to ignore empty values. Default:
Definition GetOpt.cs:106
bool IgnoreInvalidOptions
Gets or sets a value indicating whether or not invalid arguments should be ignored or not....
Definition GetOpt.cs:124
const char NonOptChar
The character that is returned when a non-option value is encountered and it is not the argument to a...
Definition GetOpt.cs:30
int ParseLongOption(out string? optArg)
Parses long options.
Definition GetOpt.cs:363
int ParseShortOption(out string? optArg)
Parses a single short option.
Definition GetOpt.cs:459
int m_currentIndex
The current index while traversing AppArgs
Definition GetOpt.cs:218
bool StopParsingOptions
Gets or sets a value indicating whether or not option parsing shall stop or not. Default:
Definition GetOpt.cs:139
bool IgnoreEmptyAppArgs
Gets or sets a value indicating whether or not empty AppArgs are ignored or throw an exception....
Definition GetOpt.cs:130
const char InvalidOptChar
The character that is returned when an invalid option is returned.
Definition GetOpt.cs:25
int CurrentIndex
Gets the current index of the app arguments being parsed.
Definition GetOpt.cs:195
const string DoubleDash
This is the string getopt.net looks for when DoubleDashStopsParsing is enabled.
Definition GetOpt.cs:35
bool IsLongOption(string arg)
Gets a value indicating whether or not the current string is a long option.
Definition GetOpt.cs:636
bool MustReturnChar1()
Gets a value indicating whether or not non-options should be handled as if they were the argument of ...

References getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.CurrentIndex, getopt.net.GetOpt.DoubleDash, getopt.net.GetOpt.DoubleDashStopsParsing, getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.IgnoreEmptyAppArgs, getopt.net.GetOpt.IgnoreEmptyOptions, getopt.net.GetOpt.IgnoreInvalidOptions, getopt.net.GetOpt.InvalidOptChar, getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsParamFileArg(), getopt.net.GetOpt.IsShortOption(), getopt.net.GetOpt.m_currentIndex, getopt.net.GetOpt.MustReturnChar1(), getopt.net.GetOpt.NonOptChar, getopt.net.GetOpt.Options, getopt.net.GetOpt.ParseLongOption(), getopt.net.GetOpt.ParseShortOption(), getopt.net.GetOpt.ReadParamFile(), getopt.net.GetOpt.ShortOpts, and getopt.net.GetOpt.StopParsingOptions.

◆ HasArgumentInOption()

bool getopt.net.GetOpt.HasArgumentInOption ( out string  optName,
out string?  argVal 
)
inlineprotected

Determines whether or not the current option contains its argument with the string or not.

Parameters
optNameOut var; the name of the option
argValOut var; the value of the argument
Returns
true
if the option contains its argument.
false
otherwise.

Definition at line 561 of file GetOpt.cs.

561 {
562 var curArg = AppArgs[CurrentIndex];
563 var splitString = default(string[]);
564
566 // if we're allowing Windows conventions, we have to replace
567 // the first occurrence of ':' in the arg string with '='
568 var indexOfSeparator = curArg.IndexOf(WinArgSeparator);
569 if (indexOfSeparator != -1) {
570 curArg = $"{ curArg.Substring(0, indexOfSeparator) }{ GnuArgSeparator }{ curArg.Substring(indexOfSeparator + 1) }";
571 }
572 }
573
574 splitString = ArgumentSplitter().Split(curArg);
575
576 if (splitString.Length == 1) {
577 optName = StripDashes(true); // we can set this to true, because this method will only ever be called for long opts
578 argVal = null;
579 return false;
580 }
581
582 optName = splitString[0];
583#if NET6_0_OR_GREATER
584 argVal = string.Join("", splitString[2..]);
585#else
586 argVal = string.Join("", splitString.Skip(2));
587#endif
588 return true;
589 }
static Regex ArgumentSplitter()
Compiled Regex.
string StripDashes(bool isLongOpt)
Strips leading dashes from strings.
Definition GetOpt.cs:599
const char WinArgSeparator
The argument separator used by Windows.
Definition GetOpt.cs:52
bool AllowWindowsConventions
Gets or sets a value indicating whether or not Windows argument conventions are allowed....
Definition GetOpt.cs:149

References getopt.net.GetOpt.AllowWindowsConventions, getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.ArgumentSplitter(), getopt.net.GetOpt.CurrentIndex, getopt.net.GetOpt.StripDashes(), and getopt.net.GetOpt.WinArgSeparator.

Referenced by getopt.net.GetOpt.ParseLongOption().

◆ IsLongOption()

bool getopt.net.GetOpt.IsLongOption ( string  arg)
inlineprotected

Gets a value indicating whether or not the current string is a long option.

Parameters
argThe string to check.
Returns
true
if the passed string is a long option.

Definition at line 636 of file GetOpt.cs.

636 {
637 if (string.IsNullOrEmpty(arg)) { return false; }
638
639 if (
641 arg.Length > 1 &&
642 arg[0] == SingleSlash &&
643 Options.Length != 0 &&
644 Options.Any(o => o.Name == arg.Split(WinArgSeparator, GnuArgSeparator, ' ')[0].Substring(1)) // We only need this option when parsing options following Windows' conventions
645 ) { return true; }
646
647 // Check for Powershell-style arguments.
648 // Powershell arguments are weird and extra checks are needed.
649 // Powershell-style arguments would theoretically interfere with short opts,
650 // so a check to determine whether or not the option is found in Options is required.
651 if (
653 arg.Length > 1 &&
654 arg[0] == SingleDash &&
655 Options.Length != 0 &&
656 Options.Any(o => o.Name == arg.Split(WinArgSeparator, GnuArgSeparator, ' ')[0].Substring(1)) // We only need this when parsing options following Powershell's conventions
657 // This parsing method is really similar to Windows option parsing...
658 ) { return true; }
659
660 return arg.Length > 2 &&
661 arg[0] == SingleDash &&
662 arg[1] == SingleDash;
663 }
const char GnuArgSeparator
The argument separator used by POSIX / GNU getopt.
Definition GetOpt.cs:57
const char SingleSlash
A single slash. This is the char that is searched for when parsing arguments with the Windows convent...
Definition GetOpt.cs:47
bool AllowPowershellConventions
Gets or sets a value indicating whether or not Powershell-style arguments are allowed....
Definition GetOpt.cs:160
const char SingleDash
A single dash character. This is the character that is searched for, when parsing POSIX-/GNU-like opt...
Definition GetOpt.cs:41

References getopt.net.GetOpt.AllowPowershellConventions, getopt.net.GetOpt.AllowWindowsConventions, getopt.net.GetOpt.GnuArgSeparator, getopt.net.GetOpt.Options, getopt.net.GetOpt.SingleDash, getopt.net.GetOpt.SingleSlash, and getopt.net.GetOpt.WinArgSeparator.

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.TryGetArgumentForShortOption().

◆ IsParamFileArg()

bool getopt.net.GetOpt.IsParamFileArg ( string  arg,
out string?  paramFile 
)
inlineprotected

Gets a value indicating whether or not a given option is a paramfile option. AllowParamFiles.

If arg is a valid paramfile option, but the file doesn't exist, paramFile will be set to

null

. Otherwise, paramFile will be set to the path to the file.

Parameters
argThe argument to check.
paramFileAn out param containing either null or the path to the file.
Returns
true
if the passed argument is a valid paramfile option.
false
otherwise.

Definition at line 696 of file GetOpt.cs.

696 {
697 paramFile = null; // pre-set this so we don't have to do it everywhere
698 if (string.IsNullOrEmpty(arg) || !AllowParamFiles || arg.Length < 2) { return false; }
699
700 if (arg[0] != SingleAtSymbol) { return false; }
701
702 arg = arg.TrimStart('@');
703
704 if (File.Exists(arg)) {
705 paramFile = arg;
706 }
707
708 return true;
709 }
bool AllowParamFiles
Gets or sets a value indicating whether or not parameter files are accepted as a valid form of input.
Definition GetOpt.cs:178
const char SingleAtSymbol
A single "at" character. This character is used when AllowParamFiles is enabled, to determine whether...
Definition GetOpt.cs:68

References getopt.net.GetOpt.AllowParamFiles, and getopt.net.GetOpt.SingleAtSymbol.

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ IsShortOption()

bool getopt.net.GetOpt.IsShortOption ( string  arg)
inlineprotected

Gets a value indicating whether or not the current string is/contains a (or more) short option.

Parameters
argThe string to check.
Returns
true
if the string contains one or more short options

Definition at line 670 of file GetOpt.cs.

670 {
671 if (string.IsNullOrEmpty(arg)) { return false; }
672
673 if (
675 arg.Length > 1 &&
676 arg[0] == SingleSlash &&
677 arg[1] != SingleSlash
678 ) { return true; }
679
680 return arg.Length > 1 &&
681 arg[0] == SingleDash &&
682 arg[1] != SingleDash;
683 }

References getopt.net.GetOpt.AllowWindowsConventions, getopt.net.GetOpt.SingleDash, and getopt.net.GetOpt.SingleSlash.

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.TryGetArgumentForShortOption().

◆ MustReturnChar1()

bool getopt.net.GetOpt.MustReturnChar1 ( )
protected

Gets a value indicating whether or not non-options should be handled as if they were the argument of an option with the character code 1.

From the getopt man page:

‍If the first character of optstring is '-', then each nonoption argv-element is handled as if it were the argument of an option with character code 1. (This is used by programs that were written to expect options and other argv-elements in any order and that care about the ordering of the two.)

Returns

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ MustStopParsing()

bool getopt.net.GetOpt.MustStopParsing ( )
protected

If the first character of ShortOpts is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered.

Returns
true
if parsing stops when the first non-option string is found.

Referenced by getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.TryGetArgumentForShortOption().

◆ ParseLongOption()

int getopt.net.GetOpt.ParseLongOption ( out string?  optArg)
inlineprotected

Parses long options.

Parameters
optArgOut var; the option's argument (if applicable)
Returns
If the option was found and no (ignored) errors were detected, the Option.Value of the argument. If an invalid option was found, '!' is returned. If a required argument is missing, '?' is returned.
Exceptions
ParseExceptionIf ignoring of errors is disabled and a parsing error occurs.

Definition at line 363 of file GetOpt.cs.

363 {
364 if (HasArgumentInOption(out var optName, out optArg)) {
365 AppArgs[m_currentIndex] = optName;
366 }
367
369
370 var nullableOpt = Options.FindOptionOrDefault(AppArgs[m_currentIndex]);
371 if (nullableOpt is null) {
374 throw new ParseException(AppArgs[m_currentIndex], "Invalid option found!");
375 }
376
377 optArg = AppArgs[m_currentIndex];
378 return InvalidOptChar;
379 }
380
381 var opt = (Option)nullableOpt;
382 switch (opt.ArgumentType) {
383 case ArgumentType.Required:
384 if (optArg == null && (IsLongOption(AppArgs[CurrentIndex + 1]) || IsShortOption(AppArgs[CurrentIndex + 1]))) {
387 return MissingArgChar;
388 } else {
389 throw new ParseException(AppArgs[CurrentIndex], "Missing required argument!");
390 }
391 } else if (optArg != null) { break; }
392
393 optArg = AppArgs[CurrentIndex + 1];
394 if (MustStopParsing()) { // POSIX behaviour desired
395 m_currentIndex = AppArgs.Length;
396 break;
397 }
398
400 break;
401 case ArgumentType.Optional:
402 // DRY this off at some point
403 if (optArg == null && !IsLongOption(AppArgs[CurrentIndex + 1]) && !IsShortOption(AppArgs[CurrentIndex + 1])) {
404 optArg = AppArgs[CurrentIndex + 1];
406 }
407 break;
408 default: // this case will handle cases where developers carelessly cast integers to the enum type
409 optArg = null;
410 break;
411 }
412
414 return opt.Value;
415 }
bool HasArgumentInOption(out string optName, out string? argVal)
Determines whether or not the current option contains its argument with the string or not.
Definition GetOpt.cs:561
bool MustStopParsing()
If the first character of ShortOpts is '+' or the environment variable POSIXLY_CORRECT is set,...
bool IgnoreMissingArgument
Gets or sets a value indicating whether or not to ignore missing arguments. Default:
Definition GetOpt.cs:115
const char MissingArgChar
The character that is returned when an option is missing a required argument.
Definition GetOpt.cs:20
ArgumentType
Enumeration containing the argument types possible for getopt.

References getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.CurrentIndex, getopt.net.GetOpt.HasArgumentInOption(), getopt.net.GetOpt.IgnoreInvalidOptions, getopt.net.GetOpt.IgnoreMissingArgument, getopt.net.GetOpt.InvalidOptChar, getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsShortOption(), getopt.net.GetOpt.m_currentIndex, getopt.net.GetOpt.MissingArgChar, getopt.net.GetOpt.MustStopParsing(), getopt.net.GetOpt.Options, and getopt.net.GetOpt.StripDashes().

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ ParseShortOption()

int getopt.net.GetOpt.ParseShortOption ( out string?  optArg)
inlineprotected

Parses a single short option.

Parameters
optArgOut var; the argument required for the option.
Returns
The current option value.
Exceptions
ParseExceptionIf ignoring of errors is disabled (default) will throw a ParseException if an error occurs.

Definition at line 459 of file GetOpt.cs.

459 {
460 optArg = null;
461 var curOpt = AppArgs[CurrentIndex][m_optPosition];
462
463 bool incrementCurrentIndex = false;
464 var argType = ShortOptRequiresArg(curOpt);
465 if (argType is null) {
468 return InvalidOptChar;
469 } else if (argType is ArgumentType type) {
470 switch (type) {
471 default:
472 if (AppArgs[CurrentIndex].Length > AppArgs[CurrentIndex].IndexOf(curOpt) + 1) {
474 return curOpt;
475 }
476 break;
477 case ArgumentType.Optional:
478 if (TryGetArgumentForShortOption(ref optArg, out incrementCurrentIndex)) {
480 if (incrementCurrentIndex) { m_currentIndex++; }
481 return curOpt;
482 }
483 break;
484 case ArgumentType.Required:
485 if (!TryGetArgumentForShortOption(ref optArg, out incrementCurrentIndex)) {
486 if (incrementCurrentIndex) { m_currentIndex++; }
488 else { throw new ParseException(curOpt.ToString(), "Missing argument for option!"); }
489 }
490 break;
491 }
492 }
493
496
497 return curOpt;
498 }
bool TryGetArgumentForShortOption(ref string? arg, out bool incrementCurrentIndex)
Attempts to retrieve the argument for the current short option.
Definition GetOpt.cs:425
ArgumentType? ShortOptRequiresArg(char shortOpt)
Gets a value indicating whether or not a short option requires an argument.
Definition GetOpt.cs:506
void ResetOptPosition()
Resets the option position to 1.
int m_optPosition
The current position in a multi-option string such as "-xvzRf" when parsing short options.
Definition GetOpt.cs:223

References getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.CurrentIndex, getopt.net.GetOpt.IgnoreMissingArgument, getopt.net.GetOpt.InvalidOptChar, getopt.net.GetOpt.m_currentIndex, getopt.net.GetOpt.m_optPosition, getopt.net.GetOpt.MissingArgChar, getopt.net.GetOpt.ResetOptPosition(), getopt.net.GetOpt.ShortOptRequiresArg(), and getopt.net.GetOpt.TryGetArgumentForShortOption().

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ ReadParamFile()

void getopt.net.GetOpt.ReadParamFile ( FileInfo  paramFile)
inlineprotected

Reads the incoming param file and adds the contents to AppArgs

Parameters
paramFileThe file to read.

Definition at line 715 of file GetOpt.cs.

715 {
716 if (paramFile == null || !paramFile.Exists) { return; }
717
718 var lastIndex = AppArgs.Length;
719 var lines = File.ReadAllLines(paramFile.FullName);
720 Array.Resize(ref m_appArgs, lines.Length + AppArgs.Length);
721
722 for (int i = lastIndex, j = 0; i < m_appArgs.Length && j < lines.Length; i++, j++) {
723 if (string.IsNullOrEmpty(lines[j].Trim())) { continue; }
724 if (lines[j].Trim()[0] == '#') { continue; }
725
726 m_appArgs[i] = lines[j];
727 }
728 }
string[] m_appArgs
Definition GetOpt.cs:86

References getopt.net.GetOpt.AppArgs, and getopt.net.GetOpt.m_appArgs.

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ ResetOptPosition()

void getopt.net.GetOpt.ResetOptPosition ( )
protected

Resets the option position to 1.

Referenced by getopt.net.GetOpt.ParseShortOption().

◆ ShallStopParsing()

static bool getopt.net.GetOpt.ShallStopParsing ( ref string  arg)
inlinestaticprotected

Gets a value indicating whether or not the parser shall stop here.

Parameters
argThe arg to check
Returns
true
if the parser shall stop parsing.
false
otherwise.

Definition at line 626 of file GetOpt.cs.

626 {
627 return !string.IsNullOrEmpty(arg) &&
628 arg.Equals("--", StringComparison.CurrentCultureIgnoreCase);
629 }

◆ ShortOptRequiresArg()

ArgumentType? getopt.net.GetOpt.ShortOptRequiresArg ( char  shortOpt)
inlineprotected

Gets a value indicating whether or not a short option requires an argument.

Parameters
shortOptThe opt to check for.
Returns
true
if the short opt requires an argument.
Exceptions
ParseExceptionIf ignoring errors is disabled (default) and an error occurs during parsing.

Definition at line 506 of file GetOpt.cs.

506 {
507 if (ShortOpts is not null && !string.IsNullOrEmpty(ShortOpts)) {
508 var posInStr = ShortOpts.IndexOf(shortOpt);
509 if (posInStr == -1) {
510 goto CheckLongOpt;
511 }
512
513 try {
514
515 char charToCheck;
516 if (posInStr < ShortOpts.Length - 1) {
517 charToCheck = ShortOpts[posInStr + 1];
518 } else {
519 charToCheck = ShortOpts[posInStr];
520 }
521
522 switch (charToCheck) {
523 case ':':
524 return ArgumentType.Required;
525 case ';':
526 return ArgumentType.Optional;
527 default:
528 return ArgumentType.None;
529 }
530 } catch {
531 goto CheckLongOpt;
532 }
533 }
534
535 CheckLongOpt:
536 if (Options.Length == 0) {
538 return null;
539 } else {
540 throw new ParseException(shortOpt.ToString(), "Invalid option list!");
541 }
542 }
543 var nullableOpt = Options.FindOptionOrDefault(shortOpt);
544
545 if (nullableOpt == null) {
547 return ArgumentType.None;
548 } else { throw new ParseException(shortOpt.ToString(), "Encountered unknown option!"); }
549 }
550
551 var opt = (Option)nullableOpt;
552 return opt.ArgumentType ?? ArgumentType.None;
553 }

References getopt.net.GetOpt.IgnoreInvalidOptions, getopt.net.GetOpt.Options, and getopt.net.GetOpt.ShortOpts.

Referenced by getopt.net.GetOpt.ParseShortOption().

◆ StripDashes()

string getopt.net.GetOpt.StripDashes ( bool  isLongOpt)
inlineprotected

Strips leading dashes from strings.

If AllowWindowsConventions is enabled, then this method will also strip leading slashes!

Parameters
isLongOptWhether or not the current option is a long option.
Returns
The stripped string

Definition at line 599 of file GetOpt.cs.

599 {
600 var curArg = AppArgs[m_currentIndex];
601
603 curArg.StartsWith(SingleSlash.ToString())) {
604 return curArg.Substring(1);
605 }
606
607 if (!curArg.StartsWith(DoubleDash) &&
608 !curArg.StartsWith(SingleDash.ToString())) {
609 return curArg;
610 }
611
612 if (isLongOpt && curArg.StartsWith(DoubleDash)) {
613 return curArg.Substring(2);
614 } else if (curArg.StartsWith(SingleDash.ToString())) {
615 return curArg.Substring(1);
616 }
617
618 return curArg;
619 }

References getopt.net.GetOpt.AllowWindowsConventions, getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.DoubleDash, getopt.net.GetOpt.m_currentIndex, getopt.net.GetOpt.SingleDash, and getopt.net.GetOpt.SingleSlash.

Referenced by getopt.net.GetOpt.HasArgumentInOption(), and getopt.net.GetOpt.ParseLongOption().

◆ TryGetArgumentForShortOption()

bool getopt.net.GetOpt.TryGetArgumentForShortOption ( ref string?  arg,
out bool  incrementCurrentIndex 
)
inlineprotected

Attempts to retrieve the argument for the current short option.

This is only a helper method to keep the code cleaner.

Parameters
argA reference to the current optArg parameter in ParseShortOption(out string?)
incrementCurrentIndexWhether or not to increment m_currentIndex
Returns
true
if an argument was found for the current option.
false
otherwise.

Definition at line 425 of file GetOpt.cs.

425 {
426 incrementCurrentIndex = false; // pre-set this
427
428 if (m_optPosition + 1 < AppArgs[CurrentIndex].Length) {
429 arg = AppArgs[CurrentIndex].Substring(m_optPosition + 1);
430 incrementCurrentIndex = true;
431 return true;
432 }
433
434 if (CurrentIndex + 1 >= AppArgs.Length) {
435 return false;
436 }
437
439 arg = AppArgs[CurrentIndex + 1];
440
441 if (MustStopParsing()) {
442 m_currentIndex = AppArgs.Length; // POSIX behaviour desired
443 } else {
444 m_currentIndex += 2;
445 }
446
447 return true;
448 }
449
450 return false;
451 }

References getopt.net.GetOpt.AppArgs, getopt.net.GetOpt.CurrentIndex, getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsShortOption(), getopt.net.GetOpt.m_currentIndex, getopt.net.GetOpt.m_optPosition, and getopt.net.GetOpt.MustStopParsing().

Referenced by getopt.net.GetOpt.ParseShortOption().

Member Data Documentation

◆ ArgSplitRegex

const string getopt.net.GetOpt.ArgSplitRegex = @"([\s]|[=])"
static

The regex used by ArgumentSplitter to split arguments into a key-value pair.

Definition at line 62 of file GetOpt.cs.

◆ DoubleDash

const string getopt.net.GetOpt.DoubleDash = "--"
static

This is the string getopt.net looks for when DoubleDashStopsParsing is enabled.

Definition at line 35 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.GetNextOpt(), and getopt.net.GetOpt.StripDashes().

◆ GnuArgSeparator

const char getopt.net.GetOpt.GnuArgSeparator = '='
static

The argument separator used by POSIX / GNU getopt.

Definition at line 57 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.IsLongOption().

◆ InvalidOptChar

const char getopt.net.GetOpt.InvalidOptChar = '!'
static

The character that is returned when an invalid option is returned.

Definition at line 25 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.ParseShortOption().

◆ m_appArgs

string [] getopt.net.GetOpt.m_appArgs = Array.Empty<string>()
private

Definition at line 86 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.ReadParamFile().

◆ m_currentIndex

int getopt.net.GetOpt.m_currentIndex = 0
protected

◆ m_optPosition

int getopt.net.GetOpt.m_optPosition = 1
protected

The current position in a multi-option string such as "-xvzRf" when parsing short options.

Definition at line 223 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.ParseShortOption(), and getopt.net.GetOpt.TryGetArgumentForShortOption().

◆ MissingArgChar

const char getopt.net.GetOpt.MissingArgChar = '?'
static

The character that is returned when an option is missing a required argument.

Definition at line 20 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.ParseShortOption().

◆ NonOptChar

const char getopt.net.GetOpt.NonOptChar = (char)1
static

The character that is returned when a non-option value is encountered and it is not the argument to an option.

Definition at line 30 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ SingleAtSymbol

const char getopt.net.GetOpt.SingleAtSymbol = '@'
static

A single "at" character. This character is used when AllowParamFiles is enabled, to determine whether or not a param file has been passed to getopt.net.

Definition at line 68 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.IsParamFileArg().

◆ SingleDash

const char getopt.net.GetOpt.SingleDash = '-'
static

A single dash character. This is the character that is searched for, when parsing POSIX-/GNU-like options.

Definition at line 41 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsShortOption(), and getopt.net.GetOpt.StripDashes().

◆ SingleSlash

const char getopt.net.GetOpt.SingleSlash = '/'
static

A single slash. This is the char that is searched for when parsing arguments with the Windows convention.

Definition at line 47 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsShortOption(), and getopt.net.GetOpt.StripDashes().

◆ WinArgSeparator

const char getopt.net.GetOpt.WinArgSeparator = ':'
static

The argument separator used by Windows.

Definition at line 52 of file GetOpt.cs.

Referenced by getopt.net.GetOpt.HasArgumentInOption(), and getopt.net.GetOpt.IsLongOption().

Property Documentation

◆ AllExceptionsDisabled

bool getopt.net.GetOpt.AllExceptionsDisabled
getset

Either enables or disabled exceptions entirely. For more specific control over exceptions, see the other options provided by GetOpt.

true if exceptions are enabled, false otherwise.

Definition at line 185 of file GetOpt.cs.

◆ AllowParamFiles

bool getopt.net.GetOpt.AllowParamFiles = false
getset

Gets or sets a value indicating whether or not parameter files are accepted as a valid form of input.

Parameter files are known from some software, such as GCC. A param file can be passed as @/path/to/file.

Param files must follow certain rules, in order to be accepted by getopt.net.

  • Param files MUST be text files, the file ending doesn't matter.
  • The contents of the file MUST be split by
    (newlines).
  • each line must be an argument acceptable by getopt.net, depending on the options set.
    • i.e. to accept Windows-convention arguments, AllowWindowsConventions must be enabled
    • to accept Powershell-convention arguments, AllowPowershellConventions must be enabled
  • paramfile arguments (@/path/to/file) may be added in addition to any other arguments!

Definition at line 178 of file GetOpt.cs.

178{ get; set; } = false;

Referenced by getopt.net.GetOpt.IsParamFileArg().

◆ AllowPowershellConventions

bool getopt.net.GetOpt.AllowPowershellConventions = false
getset

Gets or sets a value indicating whether or not Powershell-style arguments are allowed. This option doesn't conflict with the GNU/POSIX or Windows-style argument parsing and is simply an addition.

This option is disabled by default.

Powershell-style arguments are similar to GNU/POSIX long options, however they begin with a single dash (-).

Definition at line 160 of file GetOpt.cs.

160{ get; set; } = false;

Referenced by getopt.net.GetOpt.IsLongOption().

◆ AllowWindowsConventions

bool getopt.net.GetOpt.AllowWindowsConventions = false
getset

Gets or sets a value indicating whether or not Windows argument conventions are allowed. Default:

false

By convention, Windows-like options begin with a slash (/). Options with arguments are separated by a colon ':'.

Definition at line 149 of file GetOpt.cs.

149{ get; set; } = false;

Referenced by getopt.net.GetOpt.HasArgumentInOption(), getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.IsShortOption(), and getopt.net.GetOpt.StripDashes().

◆ AppArgs

◆ CurrentIndex

int getopt.net.GetOpt.CurrentIndex
get

◆ DoubleDashStopsParsing

bool getopt.net.GetOpt.DoubleDashStopsParsing = true
getset

Gets or sets a value indicating whether or not "--" stops parsing. Default:

true

Definition at line 84 of file GetOpt.cs.

84{ get; set; } = true;

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ IgnoreEmptyAppArgs

bool getopt.net.GetOpt.IgnoreEmptyAppArgs = true
getset

Gets or sets a value indicating whether or not empty AppArgs are ignored or throw an exception. Default:

true

Definition at line 130 of file GetOpt.cs.

130{ get; set; } = true;

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ IgnoreEmptyOptions

bool getopt.net.GetOpt.IgnoreEmptyOptions = true
getset

Gets or sets a value indicating whether or not to ignore empty values. Default:

true

Definition at line 106 of file GetOpt.cs.

106{ get; set; } = true;

Referenced by getopt.net.GetOpt.GetNextOpt().

◆ IgnoreInvalidOptions

bool getopt.net.GetOpt.IgnoreInvalidOptions = true
getset

Gets or sets a value indicating whether or not invalid arguments should be ignored or not. Default:

true

If this is set to

true

and an invalid argument is found, then '!' will be returned.

Definition at line 124 of file GetOpt.cs.

124{ get; set; } = true;

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.ShortOptRequiresArg().

◆ IgnoreMissingArgument

bool getopt.net.GetOpt.IgnoreMissingArgument = false
getset

Gets or sets a value indicating whether or not to ignore missing arguments. Default:

false

If this is set to

true

and a required argument is missing, '?' will be returned.

Definition at line 115 of file GetOpt.cs.

115{ get; set; } = false;

Referenced by getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.ParseShortOption().

◆ OnlyShortOpts

bool getopt.net.GetOpt.OnlyShortOpts = false
getset

Gets or sets a value indicating whether or not to only parse short options. Default:

false

Definition at line 100 of file GetOpt.cs.

100{ get; set; } = false;

◆ Options

Option [] getopt.net.GetOpt.Options = Array.Empty<Option>()
getset

An optional list of long options to go with the short options.

Definition at line 73 of file GetOpt.cs.

73{ get; set; } = Array.Empty<Option>();

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.GetOpt(), getopt.net.GetOpt.IsLongOption(), getopt.net.GetOpt.ParseLongOption(), and getopt.net.GetOpt.ShortOptRequiresArg().

◆ ShortOpts

string? getopt.net.GetOpt.ShortOpts = null
getset

The short opts to use.

Definition at line 78 of file GetOpt.cs.

78{ get; set; } = null;

Referenced by getopt.net.GetOpt.GetNextOpt(), getopt.net.GetOpt.GetOpt(), and getopt.net.GetOpt.ShortOptRequiresArg().

◆ StopParsingOptions

bool getopt.net.GetOpt.StopParsingOptions = false
getset

Gets or sets a value indicating whether or not option parsing shall stop or not. Default:

false

When this is set to

true

, all remaining arguments in AppArgs will be returned without being parsed.

Definition at line 139 of file GetOpt.cs.

139{ get; set; } = false;

Referenced by getopt.net.GetOpt.GetNextOpt().


The documentation for this class was generated from the following file: