getopt.net
A port of getopt in pure C#.
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. More...
 
 GetOpt (string[] appArgs, string shortOpts, params Option[] options)
 Specialised constructor. More...
 
int GetNextOpt (out string? outOptArg)
 Gets the next option in the list. More...
 
CommandOption GetNextOpt ()
 Gets the next option in the list, returning an object containing more detailled information about the option. More...
 

Static Public Attributes

const char MissingArgChar = '?'
 The character that is returned when an option is missing a required argument. More...
 
const char InvalidOptChar = '!'
 The character that is returned when an invalid option is returned. More...
 
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. More...
 
const string DoubleDash = "--"
 This is the string getopt.net looks for when DoubleDashStopsParsing is enabled. More...
 
const char SingleDash = '-'
 A single dash character. This is the character that is searched for, when parsing POSIX-/GNU-like options. More...
 
const char SingleSlash = '/'
 A single slash. This is the char that is searched for when parsing arguments with the Windows convention. More...
 
const char WinArgSeparator = ':'
 The argument separator used by Windows. More...
 
const char GnuArgSeparator = '='
 The argument separator used by POSIX / GNU getopt. More...
 
const string ArgSplitRegex = @"([\s]|[=])"
 The regex used by ArgumentSplitter to split arguments into a key-value pair. More...
 
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. More...
 

Protected Member Functions

void ResetOptPosition ()
 Resets the option position to 1. More...
 
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. More...
 
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. More...
 
int ParseLongOption (out string? optArg)
 Parses long options More...
 
bool TryGetArgumentForShortOption (ref string? arg, out bool incrementCurrentIndex)
 Attempts to retrieve the argument for the current short option. More...
 
int ParseShortOption (out string? optArg)
 Parses a single short option. More...
 
ArgumentTypeShortOptRequiresArg (char shortOpt)
 Gets a value indicating whether or not a short option requires an argument. More...
 
bool HasArgumentInOption (out string optName, out string? argVal)
 Determines whether or not the current option contains its argument with the string or not. More...
 
string StripDashes (bool isLongOpt)
 Strips leading dashes from strings. More...
 
bool ShallStopParsing (ref string arg)
 Gets a value indicating whether or not the parser shall stop here. More...
 
bool IsLongOption (string arg)
 Gets a value indicating whether or not the current string is a long option. More...
 
bool IsShortOption (string arg)
 Gets a value indicating whether or not the current string is/contains a (or more) short option More...
 
bool IsParamFileArg (string arg, out string? paramFile)
 Gets a value indicating whether or not a given option is a paramfile option. AllowParamFiles. More...
 
void ReadParamFile (FileInfo paramFile)
 Reads the incoming param file and adds the contents to AppArgs More...
 

Static Protected Member Functions

static Regex ArgumentSplitter ()
 Compiled Regex. More...
 

Protected Attributes

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

Properties

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

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 202 of file GetOpt.cs.

202{ }

◆ 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 210 of file GetOpt.cs.

210 {
211 AppArgs = appArgs;
212 ShortOpts = shortOpts;
213 Options = options;
214 }
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 334 of file GetOpt.cs.

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

References getopt.net.GetOpt.GetNextOpt().

Referenced by 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 272 of file GetOpt.cs.

272 {
273 if (AppArgs.Length == 0) {
274 if (!IgnoreEmptyAppArgs) {
275 throw new ParseException("No arguments found for parsing!");
276 } else {
277 outOptArg = null;
278 return -1;
279 }
280 }
281
282 outOptArg = null; // pre-set this here so we don't have to set it during every condition
283
284 if (CurrentIndex >= AppArgs.Length) { return -1; }
285
286 if (string.IsNullOrEmpty(AppArgs[m_currentIndex])) {
287 if (!IgnoreEmptyOptions) {
288 throw new ParseException("Encountered null or empty argument!");
289 } else { return 0; }
290 } else if (DoubleDashStopsParsing && AppArgs[CurrentIndex].Equals(DoubleDash, StringComparison.InvariantCultureIgnoreCase)) {
292 StopParsingOptions = true;
293 return GetNextOpt(out outOptArg);
294 }
295
296 // Check here if StopParsingOptions is true;
297 // if so, then simply return NonOptChar and set outOptArg to the value of the argument
298 if (StopParsingOptions) {
299 outOptArg = AppArgs[CurrentIndex];
301 return NonOptChar;
302 }
303
304 // Now check if the current argument is a paramfile argument
305 if (IsParamFileArg(AppArgs[CurrentIndex], out var paramFile) && paramFile is not null) {
306 ReadParamFile(new FileInfo(paramFile));
308 return GetNextOpt(out outOptArg); // We don't need to pass this back to the application. Instead just continue on
309 }
310
312 if (Options.Length == 0) { throw new ParseException("Cannot parse long option! No option list provided!"); }
313 return ParseLongOption(out outOptArg);
314 } else if (IsShortOption(AppArgs[CurrentIndex])) {
315 // check if both arg lists are empty
316 if (string.IsNullOrEmpty(ShortOpts) && Options.Length == 0) { throw new ParseException("Cannot parse short option! No option list provided!"); }
317 return ParseShortOption(out outOptArg);
318 }
319
321 outOptArg = AppArgs[CurrentIndex];
323 if (MustReturnChar1()) { return NonOptChar; }
324 else { return InvalidOptChar; }
325 } else {
326 throw new ParseException(AppArgs[CurrentIndex], "Unexpected option argument!");
327 }
328 }
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:699
bool IsShortOption(string arg)
Gets a value indicating whether or not the current string is/contains a (or more) short option
Definition: GetOpt.cs:673
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:718
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:364
int ParseShortOption(out string? optArg)
Parses a single short option.
Definition: GetOpt.cs:460
int m_currentIndex
The current index while traversing AppArgs
Definition: GetOpt.cs:219
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:196
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:639
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 564 of file GetOpt.cs.

564 {
565 var curArg = AppArgs[CurrentIndex];
566 var splitString = Array.Empty<string>();
567
569 // if we're allowing Windows conventions, we have to replace
570 // the first occurrence of ':' in the arg string with '='
571 var indexOfSeparator = curArg.IndexOf(WinArgSeparator);
572 if (indexOfSeparator != -1) {
573 curArg = $"{ curArg.Substring(0, indexOfSeparator) }{ GnuArgSeparator }{ curArg.Substring(indexOfSeparator + 1) }";
574 }
575 }
576
577 splitString = ArgumentSplitter().Split(curArg);
578
579 if (splitString.Length == 1) {
580 optName = StripDashes(true); // we can set this to true, because this method will only ever be called for long opts
581 argVal = null;
582 return false;
583 }
584
585 optName = splitString[0];
586#if NET6_0_OR_GREATER
587 argVal = string.Join("", splitString[2..]);
588#else
589 argVal = string.Join("", splitString.Skip(2));
590#endif
591 return true;
592 }
static Regex ArgumentSplitter()
Compiled Regex.
string StripDashes(bool isLongOpt)
Strips leading dashes from strings.
Definition: GetOpt.cs:602
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 639 of file GetOpt.cs.

639 {
640 if (string.IsNullOrEmpty(arg)) { return false; }
641
642 if (
644 arg.Length > 1 &&
645 arg[0] == SingleSlash &&
646 Options.Length != 0 &&
647 Options.Any(o => o.Name == arg.Split(WinArgSeparator, GnuArgSeparator, ' ').First().Substring(1)) // We only need this option when parsing options following Windows' conventions
648 ) { return true; }
649
650 // Check for Powershell-style arguments.
651 // Powershell arguments are weird and extra checks are needed.
652 // Powershell-style arguments would theoretically interfere with short opts,
653 // so a check to determine whether or not the option is found in Options is required.
654 if (
656 arg.Length > 1 &&
657 arg[0] == SingleDash &&
658 Options.Length != 0 &&
659 Options.Any(o => o.Name == arg.Split(WinArgSeparator, GnuArgSeparator, ' ').First().Substring(1)) // We only need this when parsing options following Powershell's conventions
660 // This parsing method is really similar to Windows option parsing...
661 ) { return true; }
662
663 return arg.Length > 2 &&
664 arg[0] == SingleDash &&
665 arg[1] == SingleDash;
666 }
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 699 of file GetOpt.cs.

699 {
700 paramFile = null; // pre-set this so we don't have to do it everywhere
701 if (string.IsNullOrEmpty(arg) || !AllowParamFiles || arg.Length < 2) { return false; }
702
703 if (arg[0] != SingleAtSymbol) { return false; }
704
705 arg = arg.TrimStart('@');
706
707 if (File.Exists(arg)) {
708 paramFile = arg;
709 }
710
711 return true;
712 }
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 673 of file GetOpt.cs.

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

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 364 of file GetOpt.cs.

364 {
365 if (HasArgumentInOption(out var optName, out optArg)) {
366 AppArgs[m_currentIndex] = optName;
367 }
368
370
371 var nullableOpt = Options.FindOptionOrDefault(AppArgs[m_currentIndex]);
372 if (nullableOpt is null) {
375 throw new ParseException(AppArgs[m_currentIndex], "Invalid option found!");
376 }
377
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.None:
402 default: // this case will handle cases where developers carelessly cast integers to the enum type
403 optArg = null;
404 break;
405 case ArgumentType.Optional:
406 // DRY this off at some point
407 if (optArg == null && !IsLongOption(AppArgs[CurrentIndex + 1]) && !IsShortOption(AppArgs[CurrentIndex + 1])) {
408 optArg = AppArgs[CurrentIndex + 1];
410 }
411 break;
412 }
413
415 return opt.Value;
416 }
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:564
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.
Definition: ArgumentType.cs:8

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 460 of file GetOpt.cs.

460 {
461 optArg = null;
462 var curOpt = AppArgs[CurrentIndex][m_optPosition];
463
464 bool incrementCurrentIndex = false;
465 var argType = ShortOptRequiresArg(curOpt);
466 if (argType is null) {
469 return InvalidOptChar;
470 } else if (argType is ArgumentType type) {
471 switch (type) {
472 default:
473 case ArgumentType.None:
474 if (AppArgs[CurrentIndex].Length > AppArgs[CurrentIndex].IndexOf(curOpt) + 1) {
476 return curOpt;
477 }
478 break;
479 case ArgumentType.Optional:
480 if (TryGetArgumentForShortOption(ref optArg, out incrementCurrentIndex)) {
482 if (incrementCurrentIndex) { m_currentIndex++; }
483 return curOpt;
484 }
485 break;
486 case ArgumentType.Required:
487 if (!TryGetArgumentForShortOption(ref optArg, out incrementCurrentIndex)) {
488 if (incrementCurrentIndex) { m_currentIndex++; }
490 else { throw new ParseException(curOpt.ToString(), "Missing argument for option!"); }
491 }
492 break;
493 }
494 }
495
498
499 return curOpt;
500 }
bool TryGetArgumentForShortOption(ref string? arg, out bool incrementCurrentIndex)
Attempts to retrieve the argument for the current short option.
Definition: GetOpt.cs:426
ArgumentType? ShortOptRequiresArg(char shortOpt)
Gets a value indicating whether or not a short option requires an argument.
Definition: GetOpt.cs:508
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:224

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 718 of file GetOpt.cs.

718 {
719 if (paramFile == null || !paramFile.Exists) { return; }
720
721 var lastIndex = AppArgs.Length;
722 var lines = File.ReadAllLines(paramFile.FullName);
723 Array.Resize(ref m_appArgs, lines.Length + AppArgs.Length);
724
725 for (int i = lastIndex, j = 0; i < m_appArgs.Length && j < lines.Length; i++, j++) {
726 if (string.IsNullOrEmpty(lines[j].Trim())) { continue; }
727 if (lines[j].Trim()[0] == '#') { continue; }
728
729 m_appArgs[i] = lines[j];
730 }
731 }
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()

bool getopt.net.GetOpt.ShallStopParsing ( ref string  arg)
inlineprotected

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 629 of file GetOpt.cs.

629 {
630 return !string.IsNullOrEmpty(arg) &&
631 arg.Equals("--", StringComparison.CurrentCultureIgnoreCase);
632 }

◆ 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 508 of file GetOpt.cs.

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

References getopt.net.GetOpt.IgnoreInvalidOptions, getopt.net.GetOpt.InvalidOptChar, 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 602 of file GetOpt.cs.

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

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 426 of file GetOpt.cs.

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

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(), getopt.net.GetOpt.ParseShortOption(), and getopt.net.GetOpt.ShortOptRequiresArg().

◆ 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 224 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 186 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.
  • 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: