5 // Jonathan Pryor <jpryor@novell.com>
7 // Copyright (C) 2008 Novell (http://www.novell.com)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
31 // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
33 // The LINQ version just changes the implementation of
34 // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
37 // A Getopt::Long-inspired option parsing library for C#.
39 // NDesk.Options.OptionSet is built upon a key/value table, where the
40 // key is a option format string and the value is a delegate that is
41 // invoked when the format string is matched.
43 // Option format strings:
44 // Regex-like BNF Grammar:
47 // sep: ( [^{}]+ | '{' .+ '}' )?
48 // aliases: ( name type sep ) ( '|' name type sep )*
50 // Each '|'-delimited name is an alias for the associated action. If the
51 // format string ends in a '=', it has a required value. If the format
52 // string ends in a ':', it has an optional value. If neither '=' or ':'
53 // is present, no value is supported. `=' or `:' need only be defined on one
54 // alias, but if they are provided on more than one they must be consistent.
56 // Each alias portion may also end with a "key/value separator", which is used
57 // to split option values if the option accepts > 1 value. If not specified,
58 // it defaults to '=' and ':'. If specified, it can be any character except
59 // '{' and '}' OR the *string* between '{' and '}'. If no separator should be
60 // used (i.e. the separate values should be distinct arguments), then "{}"
61 // should be used as the separator.
63 // Options are extracted either from the current option by looking for
64 // the option name followed by an '=' or ':', or is taken from the
65 // following option IFF:
66 // - The current option does not contain a '=' or a ':'
67 // - The current option requires a value (i.e. not a Option type of ':')
69 // The `name' used in the option format string does NOT include any leading
70 // option indicator, such as '-', '--', or '/'. All three of these are
71 // permitted/required on any named option.
73 // Option bundling is permitted so long as:
74 // - '-' is used to start the option group
75 // - all of the bundled options are a single character
76 // - at most one of the bundled options accepts a value, and the value
77 // provided starts from the next character to the end of the string.
79 // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
82 // Option processing is disabled by specifying "--". All options after "--"
83 // are returned by OptionSet.Parse() unchanged and unprocessed.
85 // Unprocessed options are returned from OptionSet.Parse().
89 // OptionSet p = new OptionSet ()
90 // .Add ("v", v => ++verbose)
91 // .Add ("name=|value=", v => Console.WriteLine (v));
92 // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
94 // The above would parse the argument string array, and would invoke the
95 // lambda expression three times, setting `verbose' to 3 when complete.
96 // It would also print out "A" and "B" to standard output.
97 // The returned array would contain the string "extra".
99 // C# 3.0 collection initializers are supported and encouraged:
100 // var p = new OptionSet () {
101 // { "h|?|help", v => ShowHelp () },
104 // System.ComponentModel.TypeConverter is also supported, allowing the use of
105 // custom data types in the callback type; TypeConverter.ConvertFromString()
106 // is used to convert the value option to an instance of the specified
109 // var p = new OptionSet () {
110 // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
113 // Random other tidbits:
114 // - Boolean options (those w/o '=' or ':' in the option format string)
115 // are explicitly enabled if they are followed with '+', and explicitly
116 // disabled if they are followed with '-':
118 // var p = new OptionSet () {
119 // { "a", s => a = s },
121 // p.Parse (new string[]{"-a"}); // sets v != null
122 // p.Parse (new string[]{"-a+"}); // sets v != null
123 // p.Parse (new string[]{"-a-"}); // sets v == null
125 // The NUnit version of this file introduces conditional compilation for
126 // building under the Compact Framework (NETCF) and Silverlight (SILVERLIGHT)
127 // as well as for use with a portable class library (PORTABLE).
130 // Change namespace to avoid conflict with user code use of mono.options
133 #define NUNIT_FRAMEWORK
138 using System.Collections;
139 using System.Collections.Generic;
140 using System.Collections.ObjectModel;
141 using System.ComponentModel;
142 using System.Globalization;
144 using System.Reflection;
145 //using System.Runtime.Serialization;
147 using System.Text.RegularExpressions;
150 #pragma warning disable 1591
153 using NUnit.Compatibility;
155 using System.Security.Permissions;
166 #if NUNIT_CONSOLE || NUNITLITE || NUNIT_ENGINE
167 namespace NUnit.Options
169 namespace NDesk.Options
171 namespace Mono.Options
174 public class OptionValueCollection : IList, IList<string> {
176 List<string> values = new List<string> ();
179 internal OptionValueCollection (OptionContext c)
185 void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
186 bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
187 object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
190 #region ICollection<T>
191 public void Add (string item) {values.Add (item);}
192 public void Clear () {values.Clear ();}
193 public bool Contains (string item) {return values.Contains (item);}
194 public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
195 public bool Remove (string item) {return values.Remove (item);}
196 public int Count {get {return values.Count;}}
197 public bool IsReadOnly {get {return false;}}
201 IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
204 #region IEnumerable<T>
205 public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
209 int IList.Add (object value) {return (values as IList).Add (value);}
210 bool IList.Contains (object value) {return (values as IList).Contains (value);}
211 int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
212 void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
213 void IList.Remove (object value) {(values as IList).Remove (value);}
214 void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
215 bool IList.IsFixedSize {get {return false;}}
216 object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
220 public int IndexOf (string item) {return values.IndexOf (item);}
221 public void Insert (int index, string item) {values.Insert (index, item);}
222 public void RemoveAt (int index) {values.RemoveAt (index);}
224 private void AssertValid (int index)
226 if (c.Option == null)
227 throw new InvalidOperationException ("OptionContext.Option is null.");
228 if (index >= c.Option.MaxValueCount)
229 throw new ArgumentOutOfRangeException ("index");
230 if (c.Option.OptionValueType == OptionValueType.Required &&
231 index >= values.Count)
232 throw new OptionException (string.Format (
233 c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
237 public string this [int index] {
240 return index >= values.Count ? null : values [index];
243 values [index] = value;
248 public List<string> ToList ()
250 return new List<string> (values);
253 public string[] ToArray ()
255 return values.ToArray ();
258 public override string ToString ()
260 return string.Join (", ", values.ToArray ());
264 public class OptionContext {
265 private Option option;
268 private OptionSet set;
269 private OptionValueCollection c;
271 public OptionContext (OptionSet set)
274 this.c = new OptionValueCollection (this);
277 public Option Option {
279 set {option = value;}
282 public string OptionName {
287 public int OptionIndex {
292 public OptionSet OptionSet {
296 public OptionValueCollection OptionValues {
301 public enum OptionValueType {
307 public abstract class Option {
308 string prototype, description;
310 OptionValueType type;
314 protected Option (string prototype, string description)
315 : this (prototype, description, 1)
319 protected Option (string prototype, string description, int maxValueCount)
321 if (prototype == null)
322 throw new ArgumentNullException ("prototype");
323 if (prototype.Length == 0)
324 throw new ArgumentException ("Cannot be the empty string.", "prototype");
325 if (maxValueCount < 0)
326 throw new ArgumentOutOfRangeException ("maxValueCount");
328 this.prototype = prototype;
329 this.names = prototype.Split ('|');
330 this.description = description;
331 this.count = maxValueCount;
332 this.type = ParsePrototype ();
334 if (this.count == 0 && type != OptionValueType.None)
335 throw new ArgumentException (
336 "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
337 "OptionValueType.Optional.",
339 if (this.type == OptionValueType.None && maxValueCount > 1)
340 throw new ArgumentException (
341 string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
343 if (Array.IndexOf (names, "<>") >= 0 &&
344 ((names.Length == 1 && this.type != OptionValueType.None) ||
345 (names.Length > 1 && this.MaxValueCount > 1)))
346 throw new ArgumentException (
347 "The default option handler '<>' cannot require values.",
351 public string Prototype {get {return prototype;}}
352 public string Description {get {return description;}}
353 public OptionValueType OptionValueType {get {return type;}}
354 public int MaxValueCount {get {return count;}}
356 public string[] GetNames ()
358 return (string[]) names.Clone ();
361 public string[] GetValueSeparators ()
363 if (separators == null)
364 return new string [0];
365 return (string[]) separators.Clone ();
368 protected static T Parse<T> (string value, OptionContext c)
370 Type tt = typeof (T);
372 bool nullable = tt.GetTypeInfo().IsValueType && tt.GetTypeInfo().IsGenericType &&
373 !tt.GetTypeInfo().IsGenericTypeDefinition &&
374 tt.GetGenericTypeDefinition () == typeof (Nullable<>);
375 Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
377 bool nullable = tt.IsValueType && tt.IsGenericType &&
378 !tt.IsGenericTypeDefinition &&
379 tt.GetGenericTypeDefinition () == typeof (Nullable<>);
380 Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
383 #if !NETCF && !SILVERLIGHT && !PORTABLE
384 TypeConverter conv = TypeDescriptor.GetConverter (targetType);
389 #if NETCF || SILVERLIGHT || PORTABLE
390 t = (T)Convert.ChangeType(value, tt, CultureInfo.InvariantCulture);
392 t = (T) conv.ConvertFromString (value);
395 catch (Exception e) {
396 throw new OptionException (
398 c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
399 value, targetType.Name, c.OptionName),
405 internal string[] Names {get {return names;}}
406 internal string[] ValueSeparators {get {return separators;}}
408 static readonly char[] NameTerminator = new char[]{'=', ':'};
410 private OptionValueType ParsePrototype ()
413 List<string> seps = new List<string> ();
414 for (int i = 0; i < names.Length; ++i) {
415 string name = names [i];
416 if (name.Length == 0)
417 throw new ArgumentException ("Empty option names are not supported.", "prototype");
419 int end = name.IndexOfAny (NameTerminator);
422 names [i] = name.Substring (0, end);
423 if (type == '\0' || type == name [end])
426 throw new ArgumentException (
427 string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
429 AddSeparators (name, end, seps);
433 return OptionValueType.None;
435 if (count <= 1 && seps.Count != 0)
436 throw new ArgumentException (
437 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
441 this.separators = new string[]{":", "="};
442 else if (seps.Count == 1 && seps [0].Length == 0)
443 this.separators = null;
445 this.separators = seps.ToArray ();
448 return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
451 private static void AddSeparators (string name, int end, ICollection<string> seps)
454 for (int i = end+1; i < name.Length; ++i) {
458 throw new ArgumentException (
459 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
465 throw new ArgumentException (
466 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
468 seps.Add (name.Substring (start, i-start));
473 seps.Add (name [i].ToString ());
478 throw new ArgumentException (
479 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
483 public void Invoke (OptionContext c)
488 c.OptionValues.Clear ();
491 protected abstract void OnParseComplete (OptionContext c);
493 public override string ToString ()
502 public class OptionException : Exception
504 private string option;
506 public OptionException ()
510 public OptionException (string message, string optionName)
513 this.option = optionName;
516 public OptionException (string message, string optionName, Exception innerException)
517 : base (message, innerException)
519 this.option = optionName;
522 #if !NETCF && !SILVERLIGHT && !PORTABLE
523 protected OptionException (SerializationInfo info, StreamingContext context)
524 : base (info, context)
526 this.option = info.GetString ("OptionName");
530 public string OptionName {
531 get {return this.option;}
534 #if !NETCF && !SILVERLIGHT && !PORTABLE
535 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
536 public override void GetObjectData (SerializationInfo info, StreamingContext context)
538 base.GetObjectData (info, context);
539 info.AddValue ("OptionName", option);
544 public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
546 public class OptionSet : KeyedCollection<string, Option>
550 : this (delegate (string f) {return f;})
554 public OptionSet (Converter<string, string> localizer)
556 this.localizer = localizer;
559 Converter<string, string> localizer;
561 public Converter<string, string> MessageLocalizer {
562 get {return localizer;}
565 string localizer(string msg)
570 public string MessageLocalizer(string msg)
576 protected override string GetKeyForItem (Option item)
579 throw new ArgumentNullException ("option");
580 if (item.Names != null && item.Names.Length > 0)
581 return item.Names [0];
582 // This should never happen, as it's invalid for Option to be
583 // constructed w/o any names.
584 throw new InvalidOperationException ("Option has no names!");
587 [Obsolete ("Use KeyedCollection.this[string]")]
588 protected Option GetOptionForName (string option)
591 throw new ArgumentNullException ("option");
593 return base [option];
595 catch (KeyNotFoundException) {
600 protected override void InsertItem (int index, Option item)
602 base.InsertItem (index, item);
606 protected override void RemoveItem (int index)
608 base.RemoveItem (index);
609 Option p = Items [index];
610 // KeyedCollection.RemoveItem() handles the 0th item
611 for (int i = 1; i < p.Names.Length; ++i) {
612 Dictionary.Remove (p.Names [i]);
616 protected override void SetItem (int index, Option item)
618 base.SetItem (index, item);
623 private void AddImpl (Option option)
626 throw new ArgumentNullException ("option");
627 List<string> added = new List<string> (option.Names.Length);
629 // KeyedCollection.InsertItem/SetItem handle the 0th name.
630 for (int i = 1; i < option.Names.Length; ++i) {
631 Dictionary.Add (option.Names [i], option);
632 added.Add (option.Names [i]);
636 foreach (string name in added)
637 Dictionary.Remove (name);
642 public new OptionSet Add (Option option)
648 sealed class ActionOption : Option {
649 Action<OptionValueCollection> action;
651 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
652 : base (prototype, description, count)
655 throw new ArgumentNullException ("action");
656 this.action = action;
659 protected override void OnParseComplete (OptionContext c)
661 action (c.OptionValues);
665 public OptionSet Add (string prototype, Action<string> action)
667 return Add (prototype, null, action);
670 public OptionSet Add (string prototype, string description, Action<string> action)
673 throw new ArgumentNullException ("action");
674 Option p = new ActionOption (prototype, description, 1,
675 delegate (OptionValueCollection v) { action (v [0]); });
680 public OptionSet Add (string prototype, OptionAction<string, string> action)
682 return Add (prototype, null, action);
685 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
688 throw new ArgumentNullException ("action");
689 Option p = new ActionOption (prototype, description, 2,
690 delegate (OptionValueCollection v) {action (v [0], v [1]);});
695 sealed class ActionOption<T> : Option {
698 public ActionOption (string prototype, string description, Action<T> action)
699 : base (prototype, description, 1)
702 throw new ArgumentNullException ("action");
703 this.action = action;
706 protected override void OnParseComplete (OptionContext c)
708 action (Parse<T> (c.OptionValues [0], c));
712 sealed class ActionOption<TKey, TValue> : Option {
713 OptionAction<TKey, TValue> action;
715 public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
716 : base (prototype, description, 2)
719 throw new ArgumentNullException ("action");
720 this.action = action;
723 protected override void OnParseComplete (OptionContext c)
726 Parse<TKey> (c.OptionValues [0], c),
727 Parse<TValue> (c.OptionValues [1], c));
731 public OptionSet Add<T> (string prototype, Action<T> action)
733 return Add (prototype, null, action);
736 public OptionSet Add<T> (string prototype, string description, Action<T> action)
738 return Add (new ActionOption<T> (prototype, description, action));
741 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
743 return Add (prototype, null, action);
746 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
748 return Add (new ActionOption<TKey, TValue> (prototype, description, action));
751 protected virtual OptionContext CreateOptionContext ()
753 return new OptionContext (this);
757 public List<string> Parse (IEnumerable<string> arguments)
760 OptionContext c = CreateOptionContext ();
762 var def = GetOptionForName ("<>");
764 from argument in arguments
765 where ++c.OptionIndex >= 0 && (process || def != null)
769 : !Parse (argument, c)
771 ? Unprocessed (null, def, c, argument)
775 ? Unprocessed (null, def, c, argument)
779 List<string> r = unprocessed.ToList ();
780 if (c.Option != null)
785 public List<string> Parse (IEnumerable<string> arguments)
787 OptionContext c = CreateOptionContext ();
790 List<string> unprocessed = new List<string> ();
791 Option def = Contains ("<>") ? this ["<>"] : null;
792 foreach (string argument in arguments) {
794 if (argument == "--") {
799 Unprocessed (unprocessed, def, c, argument);
802 if (!Parse (argument, c))
803 Unprocessed (unprocessed, def, c, argument);
805 if (c.Option != null)
811 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
814 extra.Add (argument);
817 c.OptionValues.Add (argument);
823 private readonly Regex ValueOption = new Regex (
824 @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
826 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
828 if (argument == null)
829 throw new ArgumentNullException ("argument");
831 flag = name = sep = value = null;
832 Match m = ValueOption.Match (argument);
836 flag = m.Groups ["flag"].Value;
837 name = m.Groups ["name"].Value;
838 if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
839 sep = m.Groups ["sep"].Value;
840 value = m.Groups ["value"].Value;
845 protected virtual bool Parse (string argument, OptionContext c)
847 if (c.Option != null) {
848 ParseValue (argument, c);
853 if (!GetOptionParts (argument, out f, out n, out s, out v))
859 c.OptionName = f + n;
861 switch (p.OptionValueType) {
862 case OptionValueType.None:
863 c.OptionValues.Add (n);
866 case OptionValueType.Optional:
867 case OptionValueType.Required:
873 // no match; is it a bool option?
874 if (ParseBool (argument, n, c))
876 // is it a bundled option?
877 if (ParseBundledValue (f, string.Concat (n + s + v), c))
883 private void ParseValue (string option, OptionContext c)
886 foreach (string o in c.Option.ValueSeparators != null
887 ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
888 : new string[]{option}) {
889 c.OptionValues.Add (o);
891 if (c.OptionValues.Count == c.Option.MaxValueCount ||
892 c.Option.OptionValueType == OptionValueType.Optional)
894 else if (c.OptionValues.Count > c.Option.MaxValueCount) {
895 throw new OptionException (localizer (string.Format (
896 "Error: Found {0} option values when expecting {1}.",
897 c.OptionValues.Count, c.Option.MaxValueCount)),
902 private bool ParseBool (string option, string n, OptionContext c)
906 if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
907 Contains ((rn = n.Substring (0, n.Length-1)))) {
909 string v = n [n.Length-1] == '+' ? option : null;
910 c.OptionName = option;
912 c.OptionValues.Add (v);
919 private bool ParseBundledValue (string f, string n, OptionContext c)
923 for (int i = 0; i < n.Length; ++i) {
925 string opt = f + n [i].ToString ();
926 string rn = n [i].ToString ();
927 if (!Contains (rn)) {
930 throw new OptionException (string.Format (localizer (
931 "Cannot bundle unregistered option '{0}'."), opt), opt);
934 switch (p.OptionValueType) {
935 case OptionValueType.None:
936 Invoke (c, opt, n, p);
938 case OptionValueType.Optional:
939 case OptionValueType.Required: {
940 string v = n.Substring (i+1);
943 ParseValue (v.Length != 0 ? v : null, c);
947 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
953 private static void Invoke (OptionContext c, string name, string value, Option option)
957 c.OptionValues.Add (value);
961 private const int OptionWidth = 29;
963 public void WriteOptionDescriptions (TextWriter o)
965 foreach (Option p in this) {
967 if (!WriteOptionPrototype (o, p, ref written))
970 if (written < OptionWidth)
971 o.Write (new string (' ', OptionWidth - written));
974 o.Write (new string (' ', OptionWidth));
978 string prefix = new string (' ', OptionWidth+2);
979 foreach (string line in GetLines (localizer (GetDescription (p.Description)))) {
988 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
990 string[] names = p.Names;
992 int i = GetNextOptionIndex (names, 0);
993 if (i == names.Length)
996 if (names [i].Length == 1) {
997 Write (o, ref written, " -");
998 Write (o, ref written, names [0]);
1001 Write (o, ref written, " --");
1002 Write (o, ref written, names [0]);
1005 for ( i = GetNextOptionIndex (names, i+1);
1006 i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1007 Write (o, ref written, ", ");
1008 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1009 Write (o, ref written, names [i]);
1012 if (p.OptionValueType == OptionValueType.Optional ||
1013 p.OptionValueType == OptionValueType.Required) {
1014 if (p.OptionValueType == OptionValueType.Optional) {
1015 Write (o, ref written, localizer ("["));
1017 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1018 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
1019 ? p.ValueSeparators [0]
1021 for (int c = 1; c < p.MaxValueCount; ++c) {
1022 Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1024 if (p.OptionValueType == OptionValueType.Optional) {
1025 Write (o, ref written, localizer ("]"));
1031 static int GetNextOptionIndex (string[] names, int i)
1033 while (i < names.Length && names [i] == "<>") {
1039 static void Write (TextWriter o, ref int n, string s)
1045 private static string GetArgumentName (int index, int maxIndex, string description)
1047 if (description == null)
1048 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1051 nameStart = new string[]{"{0:", "{"};
1053 nameStart = new string[]{"{" + index + ":"};
1054 for (int i = 0; i < nameStart.Length; ++i) {
1057 start = description.IndexOf (nameStart [i], j);
1058 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1061 int end = description.IndexOf ("}", start);
1064 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1066 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1069 private static string GetDescription (string description)
1071 if (description == null)
1072 return string.Empty;
1073 StringBuilder sb = new StringBuilder (description.Length);
1075 for (int i = 0; i < description.Length; ++i) {
1076 switch (description [i]) {
1087 if ((i+1) == description.Length || description [i+1] != '}')
1088 throw new InvalidOperationException ("Invalid option description: " + description);
1093 sb.Append (description.Substring (start, i - start));
1104 sb.Append (description [i]);
1108 return sb.ToString ();
1111 private static IEnumerable<string> GetLines (string description)
1113 if (string.IsNullOrEmpty (description)) {
1114 yield return string.Empty;
1117 int length = 80 - OptionWidth - 1;
1120 end = GetLineEnd (start, length, description);
1121 char c = description [end-1];
1122 if (char.IsWhiteSpace (c))
1124 bool writeContinuation = end != description.Length && !IsEolChar (c);
1125 string line = description.Substring (start, end - start) +
1126 (writeContinuation ? "-" : "");
1129 if (char.IsWhiteSpace (c))
1131 length = 80 - OptionWidth - 2 - 1;
1132 } while (end < description.Length);
1135 private static bool IsEolChar (char c)
1137 return !char.IsLetterOrDigit (c);
1140 private static int GetLineEnd (int start, int length, string description)
1142 int end = System.Math.Min (start + length, description.Length);
1144 for (int i = start+1; i < end; ++i) {
1145 if (description [i] == '\n')
1147 if (IsEolChar (description [i]))
1150 if (sep == -1 || end == description.Length)