5 // Jonathan Pryor <jpryor@novell.com>
6 // Federico Di Gregorio <fog@initd.org>
8 // Copyright (C) 2008 Novell (http://www.novell.com)
9 // Copyright (C) 2009 Federico Di Gregorio.
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
33 // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
35 // The LINQ version just changes the implementation of
36 // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
39 // A Getopt::Long-inspired option parsing library for C#.
41 // NDesk.Options.OptionSet is built upon a key/value table, where the
42 // key is a option format string and the value is a delegate that is
43 // invoked when the format string is matched.
45 // Option format strings:
46 // Regex-like BNF Grammar:
49 // sep: ( [^{}]+ | '{' .+ '}' )?
50 // aliases: ( name type sep ) ( '|' name type sep )*
52 // Each '|'-delimited name is an alias for the associated action. If the
53 // format string ends in a '=', it has a required value. If the format
54 // string ends in a ':', it has an optional value. If neither '=' or ':'
55 // is present, no value is supported. `=' or `:' need only be defined on one
56 // alias, but if they are provided on more than one they must be consistent.
58 // Each alias portion may also end with a "key/value separator", which is used
59 // to split option values if the option accepts > 1 value. If not specified,
60 // it defaults to '=' and ':'. If specified, it can be any character except
61 // '{' and '}' OR the *string* between '{' and '}'. If no separator should be
62 // used (i.e. the separate values should be distinct arguments), then "{}"
63 // should be used as the separator.
65 // Options are extracted either from the current option by looking for
66 // the option name followed by an '=' or ':', or is taken from the
67 // following option IFF:
68 // - The current option does not contain a '=' or a ':'
69 // - The current option requires a value (i.e. not a Option type of ':')
71 // The `name' used in the option format string does NOT include any leading
72 // option indicator, such as '-', '--', or '/'. All three of these are
73 // permitted/required on any named option.
75 // Option bundling is permitted so long as:
76 // - '-' is used to start the option group
77 // - all of the bundled options are a single character
78 // - at most one of the bundled options accepts a value, and the value
79 // provided starts from the next character to the end of the string.
81 // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
84 // Option processing is disabled by specifying "--". All options after "--"
85 // are returned by OptionSet.Parse() unchanged and unprocessed.
87 // Unprocessed options are returned from OptionSet.Parse().
91 // OptionSet p = new OptionSet ()
92 // .Add ("v", v => ++verbose)
93 // .Add ("name=|value=", v => Console.WriteLine (v));
94 // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
96 // The above would parse the argument string array, and would invoke the
97 // lambda expression three times, setting `verbose' to 3 when complete.
98 // It would also print out "A" and "B" to standard output.
99 // The returned array would contain the string "extra".
101 // C# 3.0 collection initializers are supported and encouraged:
102 // var p = new OptionSet () {
103 // { "h|?|help", v => ShowHelp () },
106 // System.ComponentModel.TypeConverter is also supported, allowing the use of
107 // custom data types in the callback type; TypeConverter.ConvertFromString()
108 // is used to convert the value option to an instance of the specified
111 // var p = new OptionSet () {
112 // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
115 // Random other tidbits:
116 // - Boolean options (those w/o '=' or ':' in the option format string)
117 // are explicitly enabled if they are followed with '+', and explicitly
118 // disabled if they are followed with '-':
120 // var p = new OptionSet () {
121 // { "a", s => a = s },
123 // p.Parse (new string[]{"-a"}); // sets v != null
124 // p.Parse (new string[]{"-a+"}); // sets v != null
125 // p.Parse (new string[]{"-a-"}); // sets v == null
129 using System.Collections;
130 using System.Collections.Generic;
131 using System.Collections.ObjectModel;
132 using System.ComponentModel;
133 using System.Globalization;
135 using System.Runtime.Serialization;
136 using System.Security.Permissions;
138 using System.Text.RegularExpressions;
149 namespace NDesk.Options
151 namespace Mono.Options
154 static class StringCoda {
156 public static IEnumerable<string> WrappedLines (string self, params int[] widths)
158 IEnumerable<int> w = widths;
159 return WrappedLines (self, w);
162 public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
165 throw new ArgumentNullException ("widths");
166 return CreateWrappedLinesIterator (self, widths);
169 private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
171 if (string.IsNullOrEmpty (self)) {
172 yield return string.Empty;
175 using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
177 int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
180 end = GetLineEnd (start, width, self);
181 char c = self [end-1];
182 if (char.IsWhiteSpace (c))
184 bool needContinuation = end != self.Length && !IsEolChar (c);
185 string continuation = "";
186 if (needContinuation) {
190 string line = self.Substring (start, end - start) + continuation;
193 if (char.IsWhiteSpace (c))
195 width = GetNextWidth (ewidths, width, ref hw);
196 } while (end < self.Length);
200 private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
202 if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
203 curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
204 // '.' is any character, - is for a continuation
205 const string minWidth = ".-";
206 if (curWidth < minWidth.Length)
207 throw new ArgumentOutOfRangeException ("widths",
208 string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
211 // no more elements, use the last element.
215 private static bool IsEolChar (char c)
217 return !char.IsLetterOrDigit (c);
220 private static int GetLineEnd (int start, int length, string description)
222 int end = System.Math.Min (start + length, description.Length);
224 for (int i = start; i < end; ++i) {
225 if (description [i] == '\n')
227 if (IsEolChar (description [i]))
230 if (sep == -1 || end == description.Length)
236 public class OptionValueCollection : IList, IList<string> {
238 List<string> values = new List<string> ();
241 internal OptionValueCollection (OptionContext c)
247 void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
248 bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
249 object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
252 #region ICollection<T>
253 public void Add (string item) {values.Add (item);}
254 public void Clear () {values.Clear ();}
255 public bool Contains (string item) {return values.Contains (item);}
256 public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
257 public bool Remove (string item) {return values.Remove (item);}
258 public int Count {get {return values.Count;}}
259 public bool IsReadOnly {get {return false;}}
263 IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
266 #region IEnumerable<T>
267 public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
271 int IList.Add (object value) {return (values as IList).Add (value);}
272 bool IList.Contains (object value) {return (values as IList).Contains (value);}
273 int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
274 void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
275 void IList.Remove (object value) {(values as IList).Remove (value);}
276 void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
277 bool IList.IsFixedSize {get {return false;}}
278 object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
282 public int IndexOf (string item) {return values.IndexOf (item);}
283 public void Insert (int index, string item) {values.Insert (index, item);}
284 public void RemoveAt (int index) {values.RemoveAt (index);}
286 private void AssertValid (int index)
288 if (c.Option == null)
289 throw new InvalidOperationException ("OptionContext.Option is null.");
290 if (index >= c.Option.MaxValueCount)
291 throw new ArgumentOutOfRangeException ("index");
292 if (c.Option.OptionValueType == OptionValueType.Required &&
293 index >= values.Count)
294 throw new OptionException (string.Format (
295 c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
299 public string this [int index] {
302 return index >= values.Count ? null : values [index];
305 values [index] = value;
310 public List<string> ToList ()
312 return new List<string> (values);
315 public string[] ToArray ()
317 return values.ToArray ();
320 public override string ToString ()
322 return string.Join (", ", values.ToArray ());
326 public class OptionContext {
327 private Option option;
330 private OptionSet set;
331 private OptionValueCollection c;
333 public OptionContext (OptionSet set)
336 this.c = new OptionValueCollection (this);
339 public Option Option {
341 set {option = value;}
344 public string OptionName {
349 public int OptionIndex {
354 public OptionSet OptionSet {
358 public OptionValueCollection OptionValues {
363 public enum OptionValueType {
369 public abstract class Option {
370 string prototype, description;
372 OptionValueType type;
376 protected Option (string prototype, string description)
377 : this (prototype, description, 1)
381 protected Option (string prototype, string description, int maxValueCount)
383 if (prototype == null)
384 throw new ArgumentNullException ("prototype");
385 if (prototype.Length == 0)
386 throw new ArgumentException ("Cannot be the empty string.", "prototype");
387 if (maxValueCount < 0)
388 throw new ArgumentOutOfRangeException ("maxValueCount");
390 this.prototype = prototype;
391 this.description = description;
392 this.count = maxValueCount;
393 this.names = (this is OptionSet.Category)
394 // append GetHashCode() so that "duplicate" categories have distinct
395 // names, e.g. adding multiple "" categories should be valid.
396 ? new[]{prototype + this.GetHashCode ()}
397 : prototype.Split ('|');
399 if (this is OptionSet.Category)
402 this.type = ParsePrototype ();
404 if (this.count == 0 && type != OptionValueType.None)
405 throw new ArgumentException (
406 "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
407 "OptionValueType.Optional.",
409 if (this.type == OptionValueType.None && maxValueCount > 1)
410 throw new ArgumentException (
411 string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
413 if (Array.IndexOf (names, "<>") >= 0 &&
414 ((names.Length == 1 && this.type != OptionValueType.None) ||
415 (names.Length > 1 && this.MaxValueCount > 1)))
416 throw new ArgumentException (
417 "The default option handler '<>' cannot require values.",
421 public string Prototype {get {return prototype;}}
422 public string Description {get {return description;}}
423 public OptionValueType OptionValueType {get {return type;}}
424 public int MaxValueCount {get {return count;}}
426 public string[] GetNames ()
428 return (string[]) names.Clone ();
431 public string[] GetValueSeparators ()
433 if (separators == null)
434 return new string [0];
435 return (string[]) separators.Clone ();
438 protected static T Parse<T> (string value, OptionContext c)
440 Type tt = typeof (T);
441 bool nullable = tt.IsValueType && tt.IsGenericType &&
442 !tt.IsGenericTypeDefinition &&
443 tt.GetGenericTypeDefinition () == typeof (Nullable<>);
444 Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
445 TypeConverter conv = TypeDescriptor.GetConverter (targetType);
449 t = (T) conv.ConvertFromString (value);
451 catch (Exception e) {
452 throw new OptionException (
454 c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
455 value, targetType.Name, c.OptionName),
461 internal string[] Names {get {return names;}}
462 internal string[] ValueSeparators {get {return separators;}}
464 static readonly char[] NameTerminator = new char[]{'=', ':'};
466 private OptionValueType ParsePrototype ()
469 List<string> seps = new List<string> ();
470 for (int i = 0; i < names.Length; ++i) {
471 string name = names [i];
472 if (name.Length == 0)
473 throw new ArgumentException ("Empty option names are not supported.", "prototype");
475 int end = name.IndexOfAny (NameTerminator);
478 names [i] = name.Substring (0, end);
479 if (type == '\0' || type == name [end])
482 throw new ArgumentException (
483 string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
485 AddSeparators (name, end, seps);
489 return OptionValueType.None;
491 if (count <= 1 && seps.Count != 0)
492 throw new ArgumentException (
493 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
497 this.separators = new string[]{":", "="};
498 else if (seps.Count == 1 && seps [0].Length == 0)
499 this.separators = null;
501 this.separators = seps.ToArray ();
504 return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
507 private static void AddSeparators (string name, int end, ICollection<string> seps)
510 for (int i = end+1; i < name.Length; ++i) {
514 throw new ArgumentException (
515 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
521 throw new ArgumentException (
522 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
524 seps.Add (name.Substring (start, i-start));
529 seps.Add (name [i].ToString ());
534 throw new ArgumentException (
535 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
539 public void Invoke (OptionContext c)
544 c.OptionValues.Clear ();
547 protected abstract void OnParseComplete (OptionContext c);
549 public override string ToString ()
555 public abstract class ArgumentSource {
557 protected ArgumentSource ()
561 public abstract string[] GetNames ();
562 public abstract string Description { get; }
563 public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
565 public static IEnumerable<string> GetArgumentsFromFile (string file)
567 return GetArguments (File.OpenText (file), true);
570 public static IEnumerable<string> GetArguments (TextReader reader)
572 return GetArguments (reader, false);
575 // Cribbed from mcs/driver.cs:LoadArgs(string)
576 static IEnumerable<string> GetArguments (TextReader reader, bool close)
579 StringBuilder arg = new StringBuilder ();
582 while ((line = reader.ReadLine ()) != null) {
585 for (int i = 0; i < t; i++) {
588 if (c == '"' || c == '\'') {
591 for (i++; i < t; i++){
598 } else if (c == ' ') {
599 if (arg.Length > 0) {
600 yield return arg.ToString ();
606 if (arg.Length > 0) {
607 yield return arg.ToString ();
619 public class ResponseFileSource : ArgumentSource {
621 public override string[] GetNames ()
623 return new string[]{"@file"};
626 public override string Description {
627 get {return "Read response file for more options.";}
630 public override bool GetArguments (string value, out IEnumerable<string> replacement)
632 if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
636 replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
642 public class OptionException : Exception {
643 private string option;
645 public OptionException ()
649 public OptionException (string message, string optionName)
652 this.option = optionName;
655 public OptionException (string message, string optionName, Exception innerException)
656 : base (message, innerException)
658 this.option = optionName;
661 protected OptionException (SerializationInfo info, StreamingContext context)
662 : base (info, context)
664 this.option = info.GetString ("OptionName");
667 public string OptionName {
668 get {return this.option;}
671 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
672 public override void GetObjectData (SerializationInfo info, StreamingContext context)
674 base.GetObjectData (info, context);
675 info.AddValue ("OptionName", option);
679 public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
681 public class OptionSet : KeyedCollection<string, Option>
684 : this (delegate (string f) {return f;})
688 public OptionSet (Converter<string, string> localizer)
690 this.localizer = localizer;
691 this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
694 Converter<string, string> localizer;
696 public Converter<string, string> MessageLocalizer {
697 get {return localizer;}
700 List<ArgumentSource> sources = new List<ArgumentSource> ();
701 ReadOnlyCollection<ArgumentSource> roSources;
703 public ReadOnlyCollection<ArgumentSource> ArgumentSources {
704 get {return roSources;}
708 protected override string GetKeyForItem (Option item)
711 throw new ArgumentNullException ("option");
712 if (item.Names != null && item.Names.Length > 0)
713 return item.Names [0];
714 // This should never happen, as it's invalid for Option to be
715 // constructed w/o any names.
716 throw new InvalidOperationException ("Option has no names!");
719 [Obsolete ("Use KeyedCollection.this[string]")]
720 protected Option GetOptionForName (string option)
723 throw new ArgumentNullException ("option");
725 return base [option];
727 catch (KeyNotFoundException) {
732 protected override void InsertItem (int index, Option item)
734 base.InsertItem (index, item);
738 protected override void RemoveItem (int index)
740 Option p = Items [index];
741 base.RemoveItem (index);
742 // KeyedCollection.RemoveItem() handles the 0th item
743 for (int i = 1; i < p.Names.Length; ++i) {
744 Dictionary.Remove (p.Names [i]);
748 protected override void SetItem (int index, Option item)
750 base.SetItem (index, item);
754 private void AddImpl (Option option)
757 throw new ArgumentNullException ("option");
758 List<string> added = new List<string> (option.Names.Length);
760 // KeyedCollection.InsertItem/SetItem handle the 0th name.
761 for (int i = 1; i < option.Names.Length; ++i) {
762 Dictionary.Add (option.Names [i], option);
763 added.Add (option.Names [i]);
767 foreach (string name in added)
768 Dictionary.Remove (name);
773 public OptionSet Add (string header)
776 throw new ArgumentNullException ("header");
777 Add (new Category (header));
781 internal sealed class Category : Option {
783 // Prototype starts with '=' because this is an invalid prototype
784 // (see Option.ParsePrototype(), and thus it'll prevent Category
785 // instances from being accidentally used as normal options.
786 public Category (string description)
787 : base ("=:Category:= " + description, description)
791 protected override void OnParseComplete (OptionContext c)
793 throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
798 public new OptionSet Add (Option option)
804 sealed class ActionOption : Option {
805 Action<OptionValueCollection> action;
807 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
808 : base (prototype, description, count)
811 throw new ArgumentNullException ("action");
812 this.action = action;
815 protected override void OnParseComplete (OptionContext c)
817 action (c.OptionValues);
821 public OptionSet Add (string prototype, Action<string> action)
823 return Add (prototype, null, action);
826 public OptionSet Add (string prototype, string description, Action<string> action)
829 throw new ArgumentNullException ("action");
830 Option p = new ActionOption (prototype, description, 1,
831 delegate (OptionValueCollection v) { action (v [0]); });
836 public OptionSet Add (string prototype, OptionAction<string, string> action)
838 return Add (prototype, null, action);
841 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
844 throw new ArgumentNullException ("action");
845 Option p = new ActionOption (prototype, description, 2,
846 delegate (OptionValueCollection v) {action (v [0], v [1]);});
851 sealed class ActionOption<T> : Option {
854 public ActionOption (string prototype, string description, Action<T> action)
855 : base (prototype, description, 1)
858 throw new ArgumentNullException ("action");
859 this.action = action;
862 protected override void OnParseComplete (OptionContext c)
864 action (Parse<T> (c.OptionValues [0], c));
868 sealed class ActionOption<TKey, TValue> : Option {
869 OptionAction<TKey, TValue> action;
871 public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
872 : base (prototype, description, 2)
875 throw new ArgumentNullException ("action");
876 this.action = action;
879 protected override void OnParseComplete (OptionContext c)
882 Parse<TKey> (c.OptionValues [0], c),
883 Parse<TValue> (c.OptionValues [1], c));
887 public OptionSet Add<T> (string prototype, Action<T> action)
889 return Add (prototype, null, action);
892 public OptionSet Add<T> (string prototype, string description, Action<T> action)
894 return Add (new ActionOption<T> (prototype, description, action));
897 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
899 return Add (prototype, null, action);
902 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
904 return Add (new ActionOption<TKey, TValue> (prototype, description, action));
907 public OptionSet Add (ArgumentSource source)
910 throw new ArgumentNullException ("source");
911 sources.Add (source);
915 protected virtual OptionContext CreateOptionContext ()
917 return new OptionContext (this);
920 public List<string> Parse (IEnumerable<string> arguments)
922 if (arguments == null)
923 throw new ArgumentNullException ("arguments");
924 OptionContext c = CreateOptionContext ();
927 List<string> unprocessed = new List<string> ();
928 Option def = Contains ("<>") ? this ["<>"] : null;
929 ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
930 foreach (string argument in ae) {
932 if (argument == "--") {
937 Unprocessed (unprocessed, def, c, argument);
940 if (AddSource (ae, argument))
942 if (!Parse (argument, c))
943 Unprocessed (unprocessed, def, c, argument);
945 if (c.Option != null)
950 class ArgumentEnumerator : IEnumerable<string> {
951 List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
953 public ArgumentEnumerator (IEnumerable<string> arguments)
955 sources.Add (arguments.GetEnumerator ());
958 public void Add (IEnumerable<string> arguments)
960 sources.Add (arguments.GetEnumerator ());
963 public IEnumerator<string> GetEnumerator ()
966 IEnumerator<string> c = sources [sources.Count-1];
968 yield return c.Current;
971 sources.RemoveAt (sources.Count-1);
973 } while (sources.Count > 0);
976 IEnumerator IEnumerable.GetEnumerator ()
978 return GetEnumerator ();
982 bool AddSource (ArgumentEnumerator ae, string argument)
984 foreach (ArgumentSource source in sources) {
985 IEnumerable<string> replacement;
986 if (!source.GetArguments (argument, out replacement))
988 ae.Add (replacement);
994 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
997 extra.Add (argument);
1000 c.OptionValues.Add (argument);
1002 c.Option.Invoke (c);
1006 private readonly Regex ValueOption = new Regex (
1007 @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
1009 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
1011 if (argument == null)
1012 throw new ArgumentNullException ("argument");
1014 flag = name = sep = value = null;
1015 Match m = ValueOption.Match (argument);
1019 flag = m.Groups ["flag"].Value;
1020 name = m.Groups ["name"].Value;
1021 if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
1022 sep = m.Groups ["sep"].Value;
1023 value = m.Groups ["value"].Value;
1028 protected virtual bool Parse (string argument, OptionContext c)
1030 if (c.Option != null) {
1031 ParseValue (argument, c);
1036 if (!GetOptionParts (argument, out f, out n, out s, out v))
1042 c.OptionName = f + n;
1044 switch (p.OptionValueType) {
1045 case OptionValueType.None:
1046 c.OptionValues.Add (n);
1047 c.Option.Invoke (c);
1049 case OptionValueType.Optional:
1050 case OptionValueType.Required:
1056 // no match; is it a bool option?
1057 if (ParseBool (argument, n, c))
1059 // is it a bundled option?
1060 if (ParseBundledValue (f, string.Concat (n + s + v), c))
1066 private void ParseValue (string option, OptionContext c)
1069 foreach (string o in c.Option.ValueSeparators != null
1070 ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
1071 : new string[]{option}) {
1072 c.OptionValues.Add (o);
1074 if (c.OptionValues.Count == c.Option.MaxValueCount ||
1075 c.Option.OptionValueType == OptionValueType.Optional)
1076 c.Option.Invoke (c);
1077 else if (c.OptionValues.Count > c.Option.MaxValueCount) {
1078 throw new OptionException (localizer (string.Format (
1079 "Error: Found {0} option values when expecting {1}.",
1080 c.OptionValues.Count, c.Option.MaxValueCount)),
1085 private bool ParseBool (string option, string n, OptionContext c)
1089 if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
1090 Contains ((rn = n.Substring (0, n.Length-1)))) {
1092 string v = n [n.Length-1] == '+' ? option : null;
1093 c.OptionName = option;
1095 c.OptionValues.Add (v);
1102 private bool ParseBundledValue (string f, string n, OptionContext c)
1106 for (int i = 0; i < n.Length; ++i) {
1108 string opt = f + n [i].ToString ();
1109 string rn = n [i].ToString ();
1110 if (!Contains (rn)) {
1113 throw new OptionException (string.Format (localizer (
1114 "Cannot bundle unregistered option '{0}'."), opt), opt);
1117 switch (p.OptionValueType) {
1118 case OptionValueType.None:
1119 Invoke (c, opt, n, p);
1121 case OptionValueType.Optional:
1122 case OptionValueType.Required: {
1123 string v = n.Substring (i+1);
1126 ParseValue (v.Length != 0 ? v : null, c);
1130 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
1136 private static void Invoke (OptionContext c, string name, string value, Option option)
1138 c.OptionName = name;
1140 c.OptionValues.Add (value);
1144 private const int OptionWidth = 29;
1145 private const int Description_FirstWidth = 80 - OptionWidth;
1146 private const int Description_RemWidth = 80 - OptionWidth - 2;
1148 public void WriteOptionDescriptions (TextWriter o)
1150 foreach (Option p in this) {
1153 Category c = p as Category;
1155 WriteDescription (o, p.Description, "", 80, 80);
1159 if (!WriteOptionPrototype (o, p, ref written))
1162 if (written < OptionWidth)
1163 o.Write (new string (' ', OptionWidth - written));
1166 o.Write (new string (' ', OptionWidth));
1169 WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
1170 Description_FirstWidth, Description_RemWidth);
1173 foreach (ArgumentSource s in sources) {
1174 string[] names = s.GetNames ();
1175 if (names == null || names.Length == 0)
1180 Write (o, ref written, " ");
1181 Write (o, ref written, names [0]);
1182 for (int i = 1; i < names.Length; ++i) {
1183 Write (o, ref written, ", ");
1184 Write (o, ref written, names [i]);
1187 if (written < OptionWidth)
1188 o.Write (new string (' ', OptionWidth - written));
1191 o.Write (new string (' ', OptionWidth));
1194 WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
1195 Description_FirstWidth, Description_RemWidth);
1199 void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
1201 bool indent = false;
1202 foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
1210 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
1212 string[] names = p.Names;
1214 int i = GetNextOptionIndex (names, 0);
1215 if (i == names.Length)
1218 if (names [i].Length == 1) {
1219 Write (o, ref written, " -");
1220 Write (o, ref written, names [0]);
1223 Write (o, ref written, " --");
1224 Write (o, ref written, names [0]);
1227 for ( i = GetNextOptionIndex (names, i+1);
1228 i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1229 Write (o, ref written, ", ");
1230 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1231 Write (o, ref written, names [i]);
1234 if (p.OptionValueType == OptionValueType.Optional ||
1235 p.OptionValueType == OptionValueType.Required) {
1236 if (p.OptionValueType == OptionValueType.Optional) {
1237 Write (o, ref written, localizer ("["));
1239 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1240 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
1241 ? p.ValueSeparators [0]
1243 for (int c = 1; c < p.MaxValueCount; ++c) {
1244 Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1246 if (p.OptionValueType == OptionValueType.Optional) {
1247 Write (o, ref written, localizer ("]"));
1253 static int GetNextOptionIndex (string[] names, int i)
1255 while (i < names.Length && names [i] == "<>") {
1261 static void Write (TextWriter o, ref int n, string s)
1267 private static string GetArgumentName (int index, int maxIndex, string description)
1269 if (description == null)
1270 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1273 nameStart = new string[]{"{0:", "{"};
1275 nameStart = new string[]{"{" + index + ":"};
1276 for (int i = 0; i < nameStart.Length; ++i) {
1279 start = description.IndexOf (nameStart [i], j);
1280 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1283 int end = description.IndexOf ("}", start);
1286 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1288 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1291 private static string GetDescription (string description)
1293 if (description == null)
1294 return string.Empty;
1295 StringBuilder sb = new StringBuilder (description.Length);
1297 for (int i = 0; i < description.Length; ++i) {
1298 switch (description [i]) {
1309 if ((i+1) == description.Length || description [i+1] != '}')
1310 throw new InvalidOperationException ("Invalid option description: " + description);
1315 sb.Append (description.Substring (start, i - start));
1326 sb.Append (description [i]);
1330 return sb.ToString ();
1333 private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
1335 return StringCoda.WrappedLines (description, firstWidth, remWidth);