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 System.Collections.ObjectModel.Collection{NDesk.Options.Option}.Add(`0) method.

Note to Inheritors

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

Members

See Also: Inherited members from object.

Constructors

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

Properties

Description [read-only]
string . A string containing documentation for this option.
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

Protected Methods

abstract OnParseComplete (NDesk.Options.OptionContext)
Perform an action when an option is parsed.

Member Details

Option Constructor

public 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, and the Option.Description property of the new instance using description.

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.

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.

Required Assembly Versions:

  • NDesk.Options 2.0.0.0
  • NDesk.Options 3.5.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 NDesk.Options.OptionSet(System.Converter{System.String,System.String}) constructor before being written to the System.IO.TextWriter instance.

Required Assembly Versions:

  • NDesk.Options 2.0.0.0
  • NDesk.Options 3.5.0.0

GetNames Method

public string[] GetNames ()

Retrieves all 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 2.0.0.0
  • NDesk.Options 3.5.0.0

Invoke Method

public void Invoke (OptionContext c)

Invokes NDesk.Options.Option.OnParseComplete(NDesk.Options.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 matching Option.GetNames is encountered with the provided value (if a value is required or optional).

Operation

This method invokes NDeks.Options.Option.OnParseComplete(OptionContext), passing along c unchanged, and then sets the following NDesk.Options.OptionContext properties on c to null:

Required Assembly Versions:

  • NDesk.Options 2.0.0.0
  • NDesk.Options 3.5.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 matching Option.GetNames is encountered with the provided value (if a value is required or optional).

Examples

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

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

class DemoOptionContext : OptionContext {
	public string OptionKey;
}

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 DemoOptionContext ();
	}

	protected override bool Parse (string option, OptionContext c)
	{
		DemoOptionContext d = (DemoOptionContext) c;
		// Prevent --a --b
		string f, n, v;
		bool haveParts = GetOptionParts (option, out f, out n, out v);
		Option nextOption = haveParts ? GetOptionForName (n.ToLower ()) : null;
		if (haveParts && c.Option != null) {
			if (nextOption == null)
				; // ignore
			else if (c.Option.OptionValueType == OptionValueType.Optional) {
				c.OptionValue = null;
				c.Option.Invoke (c);
			}
			else 
				throw new OptionException (
					string.Format ("Found option value `{0}' for option `{1}'.",
						option, c.OptionName), c.OptionName);
		}

		// option name already found, so `option' is the option value
		if (c.Option != null) {
			if (c.Option is KeyValueOption && d.OptionKey == null) {
				HandleKeyValue (option, d);
				return true;
			}
			return base.Parse (option, c);
		}

		if (!haveParts)
			// Not an option; let base handle as a non-option argument.
			return base.Parse (option, c);

		// use lower-case version of the option name.
		if (nextOption != null && nextOption is KeyValueOption) {
			d.Option     = nextOption;
			d.OptionName = f + n.ToLower ();
			HandleKeyValue (v, d);
			return true;
		}
		return base.Parse (f + n.ToLower () + (v != null ? "=" + v : ""), c);
	}

	static void HandleKeyValue (string option, DemoOptionContext d)
	{
		if (option == null)
			return;
		string[] parts = option.Split ('=');
		if (parts.Length == 1) {
			d.OptionKey = option;
			return;
		}
		d.OptionKey   = parts [0];
		d.OptionValue = parts [1];
		if (d.Option != null) {
			d.Option.Invoke (d);
		}
	}

	class KeyValueOption : Option {
		public KeyValueOption (string prototype, Action<string,string,OptionContext> action)
			: base (prototype, null)
		{
			this.action = action;
		}

		Action<string,string,OptionContext> action;

		protected override void OnParseComplete (OptionContext c)
		{
			DemoOptionContext d = (DemoOptionContext) c;
			action (d.OptionKey, d.OptionValue, d);
			d.OptionKey = null;
		}
	}

	public new DemoOptionSet Add (string prototype,
		Action<string,string,OptionContext> action)
	{
		base.Add (new KeyValueOption (prototype, action));
		return this;
	}
}

class Demo {
	public static void Main (string[] args)
	{
		bool show_help = false;
		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,c) => 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 2.0.0.0
  • NDesk.Options 3.5.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 2.0.0.0
  • NDesk.Options 3.5.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.

Required Assembly Versions:

  • NDesk.Options 2.0.0.0
  • NDesk.Options 3.5.0.0

ToString Method

public override string ToString ()

Returns Option.Prototype.

Returns

A string containing Option.Prototype.

Remarks

Required Assembly Versions:

  • NDesk.Options 2.0.0.0
  • NDesk.Options 3.5.0.0