NDesk.Options

GIT Repository

NDesk.Options : NDesk.Options Namespace

Option Class

Represents information about an option.

public abstract class Option


Thread Safety

All members of this type are safe for multithreaded operations. Subclasses must be thread-safe if multithreaded invocation of OptionSet.Parse(System.Collections.Generic.IEnumerable<string>) is required.

Remarks

Instances of NDesk.Options.Option are created via the various NDesk.Options.OptionSetAdd overloads, such as:

You can also add custom NDesk.Options.Option subclasses to an NDesk.Options.OptionSet via the OptionSet.Add(Option) method.

Note to Inheritors

Inheritors of this type must override the abstract method Option.OnParseComplete(OptionContext), which is (indirectly) invoked from within OptionSet.Parse(string, OptionContext) when an option matching one of the prototype aliases is encountered.

Members

See Also: Inherited members from object.

Protected Constructors

Creates and initializes a new instance of the NDesk.Options.Option class.
Creates and initializes a new instance of the NDesk.Options.Option class.

Properties

Description [read-only]
string . A string containing documentation for this option.
MaxValueCount [read-only]
int . A int containing the maximum number of values this NDesk.Options.Option accepts.
OptionValueType [read-only]
NDesk.Options.OptionValueType . An NDesk.Options.OptionValueType instance specifying whether this NDesk.Options.Option takes a value, and if so, whether it's required or optional.
Prototype [read-only]
string . The NDesk.Options.Option prototype, containing option name aliases and the option value requirements.

Methods

GetNames () : string[]
Retrieves all name aliases that make up Option.Prototype.
GetValueSeparators () : string[]
Retreives all value separators, strings which are used to split an argument into one or more values for the this NDesk.Options.Option.
Invoke (NDesk.Options.OptionContext)
Invokes Option.OnParseComplete(OptionContext) then clears out c.
override ToString () : string
Returns Option.Prototype.

Protected Methods

abstract OnParseComplete (NDesk.Options.OptionContext)
Perform an action when an option is parsed.
static Parse<T> (string, NDesk.Options.OptionContext) : T
Converts the stringvalue into an object of type T.

Member Details

Option Constructor

protected Option (string prototype, string description)

Creates and initializes a new instance of the NDesk.Options.Option class.

Parameters

prototype
A string containing a |-separated list of option names (aliases) and an optional value-type specifier.
description
A string containing documentation for the option.

Exceptions

Type Condition
ArgumentException

prototype is the empty string "".

-or-

prototype contains an empty alias, such as a||b.

-or-

Conflicting NDesk.Options.OptionValueType values were found within prototype.

ArgumentNullException prototype is null.

Remarks

This constructor initializes the Option.Prototype property of the new instance using prototype, the Option.Description property of the new instance using description. and initializes the Option.MaxValueCount property of the new instance to 1.

This is equivalent to calling the Option(string, string, int) constructor as with Option(prototype, description, 1).

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

Option Constructor

protected Option (string prototype, string description, int maxValueCount)

Creates and initializes a new instance of the NDesk.Options.Option class.

Parameters

prototype
A string containing a |-separated list of option names (aliases) and an optional value-type specifier.
description
A string containing documentation for the option.
maxValueCount
A int containing the number of values this option accepts.

Exceptions

Type Condition
ArgumentException

prototype is the empty string "".

-or-

prototype contains an empty alias, such as a||b.

-or-

Conflicting NDesk.Options.OptionValueType values were found within prototype.

-or-

maxValueCount is 0 and prototype specified an NDesk.Options.OptionValueType value of OptionValueType.Optional or OptionValueType.Required.

-or-

maxValueCount is greater than 1 and prototype specified an NDesk.Options.OptionValueType value of OptionValueType.None.

-or-

prototype contains a separator list and maxValueCount is 0 or 1.

-or-

prototype contains a badly formatted separator list, such as {{, }}, {{}, etc.

ArgumentNullException prototype is null.

Remarks

This constructor initializes the Option.Prototype property of the new instance using prototype, the Option.Description property of the new instance using description. and initializes the Option.MaxValueCount property of the new instance using maxValueCount.

prototype is a |-separated list of option names. It should be listed in shortest-to-longest order, e.g. h|help. prototype may contain a NDesk.Options.OptionValueType specifier following one of the |-separated entries, and a value separator list following the NDesk.Options.OptionValueType specifier.

The Option.OptionValueType property is initialized based on whether a = or : follows one of the aliases within prototype. = specifies a OptionValueType.Required value, while : specifies an OptionValueType.Optional value. If neither = nor : is not specified, then OptionValueType.None is used. The value specifier may be used anywhere within prototype, so n|name=, n=|name and n=|name= are equivalent, but you cannot mix types; n:|name= is invalid.

Multiple values may be bundled together, such as -opt key=value. The value separator list specifies which characters can be used to split the value argument to generate separate values. The value separator list is available when maxValueCount is greater than 1, and and an NDesk.Options.OptionValueType was specified. The value separator list follows the = or : and is one of the following:

  • A sequence of character enclosed by { and }. Multiple such sequences may be specified by listing the {...} sequence multiple times.

    The sequence {} requires that each value be a different argument, and no argument splitting will be performed. This sequence has no effect if other separators are also listed (as separate arguments are always permitted for OptionValueType.Required values).

  • Any literal character other than { and }.

If the separator list is not provided, then =: is the default separator list.

For example, the prototype "A:+-*/" would permit any of `+', `-', `*', or `/' to be used to split an argument into values, so -A:5/2 would generate the sequence of values 5 and 2 for the option -A. Furthermore, the prototype "A={-->}{=>}" would permit either the string --> or the string => to be used, so -A A->B C woud parse A->B as one value and C as the other value, while -A A-->B C would parse A as one value and B as the other value while C would be unhandled (unless the option required 3 values, in which case C would be the 3rd value).

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

Description Property

public string Description { get; }

A string containing documentation for this option.

See Also

Value

A string containing documentation for this option.

Remarks

This property is used to generate documentation within OptionSet.WriteOptionDescriptions(System.IO.TextWriter). The string returned is translated via the localizer parameter provided to the OptionSet(Converter<string, string>) constructor before being written to the System.IO.TextWriter instance.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

GetNames Method

public string[] GetNames ()

Retrieves all name aliases that make up Option.Prototype.

Returns

A string array containing all name aliases for this NDesk.Options.Option instance.

Remarks

The returned option names will not contain any NDesk.Options.OptionValueType specifier that may be within Option.Prototype. If Option.Prototype is a=|b=|c=, the array returned will contain a, b, and c.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

GetValueSeparators Method

public string[] GetValueSeparators ()

Retreives all value separators, strings which are used to split an argument into one or more values for the this NDesk.Options.Option.

Returns

A string array containing all strings that should be used when splitting an argument into one or more values for this NDesk.Options.Option.

Remarks

Value separators may be provided within Option.Prototype only if:

See the Option(string, string, int) constructor for more information.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

Invoke Method

public void Invoke (OptionContext c)

Invokes Option.OnParseComplete(OptionContext) then clears out c.

See Also

Parameters

c
An NDesk.Options.OptionContext instance containing information about the option that was parsed.

Remarks

This method is invoked from within OptionSet.Parse(string, OptionContext) when an option with a name from Option.GetNames is encountered and matches the required number of values governed by Option.OptionValueType and Option.MaxValueCount.

Operation

This method invokes Option.OnParseComplete(OptionContext), passing along c unchanged, and then sets the OptionContext.Option and OptionContext.OptionName properties to null, and OptionValueCollection.Clears out OptionContext.OptionValues.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

MaxValueCount Property

public int MaxValueCount { get; }

A int containing the maximum number of values this NDesk.Options.Option accepts.

Value

A int containing the maximum number of values this NDesk.Options.Option accepts.

Remarks

This is a maximum, and may not be the number of values present within OptionContext.OptionValues when Option.OnParseComplete(OptionContext) is invoked. There will be Option.MaxValueCount values if Option.OptionValueType is OptionValueType.Required, but if Option.OptionValueType is OptionValueType.Optional then OptionContext.OptionValues may contain fewer items.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

OnParseComplete Method

protected abstract void OnParseComplete (OptionContext c)

Perform an action when an option is parsed.

See Also

Parameters

c
An NDesk.Options.OptionContext instance containing information about the option that was parsed.

Remarks

This method must be overridden by all subclasses, within which the subclass can perform some custom per-option processing.

This method is invoked from within OptionSet.Parse(string, OptionContext) when an option with a name from Option.GetNames is encountered and matches the required number of values governed by Option.OptionValueType and Option.MaxValueCount.

Examples

The following example has a custom NDesk.Options.Option subclass which overrides Option.OnParseComplete(OptionContext):

C# Example
// Case-Insensitive and Concatenating OptionSet
using System;
using System.Collections.Generic;
using NDesk.Options;

class DemoOptionSet : OptionSet {
	protected override void InsertItem (int index, Option item)
	{
		if (item.Prototype.ToLower () != item.Prototype)
			throw new ArgumentException ("prototypes must be lower-case!");
		base.InsertItem (index, item);
	}

	protected override OptionContext CreateOptionContext ()
	{
		return new OptionContext (this);
	}

	protected override bool Parse (string option, OptionContext c)
	{
		string f, n, s, v;
		bool haveParts = GetOptionParts (option, out f, out n, out s, out v);
		Option nextOption = null;
		string newOption  = option;

		if (haveParts) {
			nextOption = GetOptionForName (n.ToLower ());
			newOption = f + n.ToLower () + (v != null ? s + v : "");
		}

		if (c.Option != null) {
			// Prevent --a --b
			if (c.Option != null && haveParts) {
				if (nextOption == null) {
					// ignore
				}
				else 
					throw new OptionException (
						string.Format ("Found option `{0}' as value for option `{1}'.",
							option, c.OptionName), c.OptionName);
			}

			// have a option w/ required value; try to concat values.
			if (AppendValue (option, c)) {
				if (!option.EndsWith ("\\") && 
						c.Option.MaxValueCount == c.OptionValues.Count) {
					c.Option.Invoke (c);
				}
				return true;
			}
			else
				base.Parse (newOption, c);
		}

		if (!haveParts || v == null) {
			// Not an option; let base handle as a non-option argument.
			return base.Parse (newOption, c);
		}

		if (nextOption.OptionValueType != OptionValueType.None && 
				v.EndsWith ("\\")) {
			c.Option = nextOption;
			c.OptionValues.Add (v);
			c.OptionName = f + n;
			return true;
		}

		return base.Parse (newOption, c);
	}

	private bool AppendValue (string value, OptionContext c)
	{
		bool added = false;
		string[] seps = c.Option.GetValueSeparators ();
		foreach (var o in seps.Length != 0
				? value.Split (seps, StringSplitOptions.None)
				: new string[]{value}) {
			int idx = c.OptionValues.Count-1;
			if (idx == -1 || !c.OptionValues [idx].EndsWith ("\\")) {
				c.OptionValues.Add (o);
				added = true;
			}
			else {
				c.OptionValues [idx] += value;
				added = true;
			}
		}
		return added;
	}
}

class Demo {
	public static void Main (string[] args)
	{
		List<string> names = new List<string> ();
		Dictionary<string,string> map = new Dictionary<string,string> ();
		int repeat = 1;

		OptionSet p = new DemoOptionSet () {
			{ "n|name=",    v => names.Add (v) },
			{ "r|repeat:",  (int v) => repeat = v },
			{ "m|map=",     (k,v) => map.Add (k, v) },
		};

		List<string> extra;
		try {
			extra = p.Parse (args);
		}
		catch (OptionException e) {
			Console.Write ("subclass: ");
			Console.WriteLine (e.Message);
			return;
		}

		string message;
		if (extra.Count > 0) {
			message = string.Join (" ", extra.ToArray ());
		}
		else {
			message = "Hello {0}!";
		}

		foreach (string name in names) {
			for (int i = 0; i < repeat; ++i)
				Console.WriteLine (message, name);
		}
		List<string> keys = new List<string>(map.Keys);
		keys.Sort ();
		foreach (string key in keys) {
			Console.WriteLine ("Key: {0}={1}", key, map [key]);
		}
	}
}

See NDesk.Options.OptionSet for more on this example.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

OptionValueType Property

public OptionValueType OptionValueType { get; }

An NDesk.Options.OptionValueType instance specifying whether this NDesk.Options.Option takes a value, and if so, whether it's required or optional.

Value

An NDesk.Options.OptionValueType specifying whether a value is required for this value.

Remarks

This is initialized based on the presence of = or : within Option.Prototype.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

Parse<T> Generic Method

protected static T Parse<T> (string value, OptionContext c)

Converts the stringvalue into an object of type T.

Type Parameters

T
The type to convert the string value to.

Parameters

value
A string containing a representation of the type T that should be converted into an instance of type T.
c
A NDesk.Options.OptionContext containing additional contextual information needed error handling.

Returns

If value is null, then default(T) is returned. Otherwise, value is converted to a value of type T.

Exceptions

Type Condition
NDesk.Options.OptionException If value is not null and System.ComponentModel.TypeConverter.ConvertFromString generated an exception while trying to convert value.

Remarks

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

Prototype Property

public string Prototype { get; }

The NDesk.Options.Option prototype, containing option name aliases and the option value requirements.

Value

A string containing the prototype of this NDesk.Options.Option instance.

Remarks

The prototype contains a |-separated list of all option name aliases and a value specifier of = for required values and : for optional values; if neither = nor : is present, no value is taken.

If a value specifier is present, then a value separator list may also be present after the value specifier.

Required Assembly Versions:

  • NDesk.Options 0.2.0.0

ToString Method

public override string ToString ()

Returns Option.Prototype.

Returns

A string containing Option.Prototype.

Remarks

Required Assembly Versions:

  • NDesk.Options 0.2.0.0