5 // Jonathan Pryor <jpryor@novell.com>
6 // Federico Di Gregorio <fog@initd.org>
7 // Rolf Bjarne Kvinge <rolf@xamarin.com>
9 // Copyright (C) 2008 Novell (http://www.novell.com)
10 // Copyright (C) 2009 Federico Di Gregorio.
11 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
35 // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
37 // The LINQ version just changes the implementation of
38 // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
41 // A Getopt::Long-inspired option parsing library for C#.
43 // NDesk.Options.OptionSet is built upon a key/value table, where the
44 // key is a option format string and the value is a delegate that is
45 // invoked when the format string is matched.
47 // Option format strings:
48 // Regex-like BNF Grammar:
51 // sep: ( [^{}]+ | '{' .+ '}' )?
52 // aliases: ( name type sep ) ( '|' name type sep )*
54 // Each '|'-delimited name is an alias for the associated action. If the
55 // format string ends in a '=', it has a required value. If the format
56 // string ends in a ':', it has an optional value. If neither '=' or ':'
57 // is present, no value is supported. `=' or `:' need only be defined on one
58 // alias, but if they are provided on more than one they must be consistent.
60 // Each alias portion may also end with a "key/value separator", which is used
61 // to split option values if the option accepts > 1 value. If not specified,
62 // it defaults to '=' and ':'. If specified, it can be any character except
63 // '{' and '}' OR the *string* between '{' and '}'. If no separator should be
64 // used (i.e. the separate values should be distinct arguments), then "{}"
65 // should be used as the separator.
67 // Options are extracted either from the current option by looking for
68 // the option name followed by an '=' or ':', or is taken from the
69 // following option IFF:
70 // - The current option does not contain a '=' or a ':'
71 // - The current option requires a value (i.e. not a Option type of ':')
73 // The `name' used in the option format string does NOT include any leading
74 // option indicator, such as '-', '--', or '/'. All three of these are
75 // permitted/required on any named option.
77 // Option bundling is permitted so long as:
78 // - '-' is used to start the option group
79 // - all of the bundled options are a single character
80 // - at most one of the bundled options accepts a value, and the value
81 // provided starts from the next character to the end of the string.
83 // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
86 // Option processing is disabled by specifying "--". All options after "--"
87 // are returned by OptionSet.Parse() unchanged and unprocessed.
89 // Unprocessed options are returned from OptionSet.Parse().
93 // OptionSet p = new OptionSet ()
94 // .Add ("v", v => ++verbose)
95 // .Add ("name=|value=", v => Console.WriteLine (v));
96 // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
98 // The above would parse the argument string array, and would invoke the
99 // lambda expression three times, setting `verbose' to 3 when complete.
100 // It would also print out "A" and "B" to standard output.
101 // The returned array would contain the string "extra".
103 // C# 3.0 collection initializers are supported and encouraged:
104 // var p = new OptionSet () {
105 // { "h|?|help", v => ShowHelp () },
108 // System.ComponentModel.TypeConverter is also supported, allowing the use of
109 // custom data types in the callback type; TypeConverter.ConvertFromString()
110 // is used to convert the value option to an instance of the specified
113 // var p = new OptionSet () {
114 // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
117 // Random other tidbits:
118 // - Boolean options (those w/o '=' or ':' in the option format string)
119 // are explicitly enabled if they are followed with '+', and explicitly
120 // disabled if they are followed with '-':
122 // var p = new OptionSet () {
123 // { "a", s => a = s },
125 // p.Parse (new string[]{"-a"}); // sets v != null
126 // p.Parse (new string[]{"-a+"}); // sets v != null
127 // p.Parse (new string[]{"-a-"}); // sets v == null
131 using System.Collections;
132 using System.Collections.Generic;
133 using System.Collections.ObjectModel;
134 using System.ComponentModel;
135 using System.Globalization;
137 using System.Runtime.Serialization;
139 using System.Reflection;
141 using System.Security.Permissions;
144 using System.Text.RegularExpressions;
155 using MessageLocalizerConverter = System.Func<string, string>;
157 using MessageLocalizerConverter = System.Converter<string, string>;
161 namespace NDesk.Options
163 namespace Mono.Options
166 static class StringCoda {
168 public static IEnumerable<string> WrappedLines (string self, params int[] widths)
170 IEnumerable<int> w = widths;
171 return WrappedLines (self, w);
174 public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
177 throw new ArgumentNullException ("widths");
178 return CreateWrappedLinesIterator (self, widths);
181 private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
183 if (string.IsNullOrEmpty (self)) {
184 yield return string.Empty;
187 using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
189 int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
192 end = GetLineEnd (start, width, self);
193 char c = self [end-1];
194 if (char.IsWhiteSpace (c))
196 bool needContinuation = end != self.Length && !IsEolChar (c);
197 string continuation = "";
198 if (needContinuation) {
202 string line = self.Substring (start, end - start) + continuation;
205 if (char.IsWhiteSpace (c))
207 width = GetNextWidth (ewidths, width, ref hw);
208 } while (start < self.Length);
212 private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
214 if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
215 curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
216 // '.' is any character, - is for a continuation
217 const string minWidth = ".-";
218 if (curWidth < minWidth.Length)
219 throw new ArgumentOutOfRangeException ("widths",
220 string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
223 // no more elements, use the last element.
227 private static bool IsEolChar (char c)
229 return !char.IsLetterOrDigit (c);
232 private static int GetLineEnd (int start, int length, string description)
234 int end = System.Math.Min (start + length, description.Length);
236 for (int i = start; i < end; ++i) {
237 if (description [i] == '\n')
239 if (IsEolChar (description [i]))
242 if (sep == -1 || end == description.Length)
248 public class OptionValueCollection : IList, IList<string> {
250 List<string> values = new List<string> ();
253 internal OptionValueCollection (OptionContext c)
259 void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
260 bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
261 object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
264 #region ICollection<T>
265 public void Add (string item) {values.Add (item);}
266 public void Clear () {values.Clear ();}
267 public bool Contains (string item) {return values.Contains (item);}
268 public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
269 public bool Remove (string item) {return values.Remove (item);}
270 public int Count {get {return values.Count;}}
271 public bool IsReadOnly {get {return false;}}
275 IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
278 #region IEnumerable<T>
279 public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
283 int IList.Add (object value) {return (values as IList).Add (value);}
284 bool IList.Contains (object value) {return (values as IList).Contains (value);}
285 int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
286 void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
287 void IList.Remove (object value) {(values as IList).Remove (value);}
288 void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
289 bool IList.IsFixedSize {get {return false;}}
290 object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
294 public int IndexOf (string item) {return values.IndexOf (item);}
295 public void Insert (int index, string item) {values.Insert (index, item);}
296 public void RemoveAt (int index) {values.RemoveAt (index);}
298 private void AssertValid (int index)
300 if (c.Option == null)
301 throw new InvalidOperationException ("OptionContext.Option is null.");
302 if (index >= c.Option.MaxValueCount)
303 throw new ArgumentOutOfRangeException ("index");
304 if (c.Option.OptionValueType == OptionValueType.Required &&
305 index >= values.Count)
306 throw new OptionException (string.Format (
307 c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
311 public string this [int index] {
314 return index >= values.Count ? null : values [index];
317 values [index] = value;
322 public List<string> ToList ()
324 return new List<string> (values);
327 public string[] ToArray ()
329 return values.ToArray ();
332 public override string ToString ()
334 return string.Join (", ", values.ToArray ());
338 public class OptionContext {
339 private Option option;
342 private OptionSet set;
343 private OptionValueCollection c;
345 public OptionContext (OptionSet set)
348 this.c = new OptionValueCollection (this);
351 public Option Option {
353 set {option = value;}
356 public string OptionName {
361 public int OptionIndex {
366 public OptionSet OptionSet {
370 public OptionValueCollection OptionValues {
375 public enum OptionValueType {
381 public abstract class Option {
382 string prototype, description;
384 OptionValueType type;
389 protected Option (string prototype, string description)
390 : this (prototype, description, 1, false)
394 protected Option (string prototype, string description, int maxValueCount)
395 : this (prototype, description, maxValueCount, false)
399 protected Option (string prototype, string description, int maxValueCount, bool hidden)
401 if (prototype == null)
402 throw new ArgumentNullException ("prototype");
403 if (prototype.Length == 0)
404 throw new ArgumentException ("Cannot be the empty string.", "prototype");
405 if (maxValueCount < 0)
406 throw new ArgumentOutOfRangeException ("maxValueCount");
408 this.prototype = prototype;
409 this.description = description;
410 this.count = maxValueCount;
411 this.names = (this is OptionSet.Category)
412 // append GetHashCode() so that "duplicate" categories have distinct
413 // names, e.g. adding multiple "" categories should be valid.
414 ? new[]{prototype + this.GetHashCode ()}
415 : prototype.Split ('|');
417 if (this is OptionSet.Category)
420 this.type = ParsePrototype ();
421 this.hidden = hidden;
423 if (this.count == 0 && type != OptionValueType.None)
424 throw new ArgumentException (
425 "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
426 "OptionValueType.Optional.",
428 if (this.type == OptionValueType.None && maxValueCount > 1)
429 throw new ArgumentException (
430 string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
432 if (Array.IndexOf (names, "<>") >= 0 &&
433 ((names.Length == 1 && this.type != OptionValueType.None) ||
434 (names.Length > 1 && this.MaxValueCount > 1)))
435 throw new ArgumentException (
436 "The default option handler '<>' cannot require values.",
440 public string Prototype {get {return prototype;}}
441 public string Description {get {return description;}}
442 public OptionValueType OptionValueType {get {return type;}}
443 public int MaxValueCount {get {return count;}}
444 public bool Hidden {get {return hidden;}}
446 public string[] GetNames ()
448 return (string[]) names.Clone ();
451 public string[] GetValueSeparators ()
453 if (separators == null)
454 return new string [0];
455 return (string[]) separators.Clone ();
458 protected static T Parse<T> (string value, OptionContext c)
460 Type tt = typeof (T);
462 TypeInfo ti = tt.GetTypeInfo ();
469 !ti.IsGenericTypeDefinition &&
470 ti.GetGenericTypeDefinition () == typeof (Nullable<>);
472 Type targetType = nullable ? tt.GenericTypeArguments [0] : tt;
474 Type targetType = nullable ? tt.GetGenericArguments () [0] : tt;
480 if (targetType.GetTypeInfo ().IsEnum)
481 t = (T) Enum.Parse (targetType, value, true);
483 t = (T) Convert.ChangeType (value, targetType);
485 TypeConverter conv = TypeDescriptor.GetConverter (targetType);
486 t = (T) conv.ConvertFromString (value);
490 catch (Exception e) {
491 throw new OptionException (
493 c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
494 value, targetType.Name, c.OptionName),
500 internal string[] Names {get {return names;}}
501 internal string[] ValueSeparators {get {return separators;}}
503 static readonly char[] NameTerminator = new char[]{'=', ':'};
505 private OptionValueType ParsePrototype ()
508 List<string> seps = new List<string> ();
509 for (int i = 0; i < names.Length; ++i) {
510 string name = names [i];
511 if (name.Length == 0)
512 throw new ArgumentException ("Empty option names are not supported.", "prototype");
514 int end = name.IndexOfAny (NameTerminator);
517 names [i] = name.Substring (0, end);
518 if (type == '\0' || type == name [end])
521 throw new ArgumentException (
522 string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
524 AddSeparators (name, end, seps);
528 return OptionValueType.None;
530 if (count <= 1 && seps.Count != 0)
531 throw new ArgumentException (
532 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
536 this.separators = new string[]{":", "="};
537 else if (seps.Count == 1 && seps [0].Length == 0)
538 this.separators = null;
540 this.separators = seps.ToArray ();
543 return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
546 private static void AddSeparators (string name, int end, ICollection<string> seps)
549 for (int i = end+1; i < name.Length; ++i) {
553 throw new ArgumentException (
554 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
560 throw new ArgumentException (
561 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
563 seps.Add (name.Substring (start, i-start));
568 seps.Add (name [i].ToString ());
573 throw new ArgumentException (
574 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
578 public void Invoke (OptionContext c)
583 c.OptionValues.Clear ();
586 protected abstract void OnParseComplete (OptionContext c);
588 public override string ToString ()
594 public abstract class ArgumentSource {
596 protected ArgumentSource ()
600 public abstract string[] GetNames ();
601 public abstract string Description { get; }
602 public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
605 public static IEnumerable<string> GetArgumentsFromFile (string file)
607 return GetArguments (File.OpenText (file), true);
611 public static IEnumerable<string> GetArguments (TextReader reader)
613 return GetArguments (reader, false);
616 // Cribbed from mcs/driver.cs:LoadArgs(string)
617 static IEnumerable<string> GetArguments (TextReader reader, bool close)
620 StringBuilder arg = new StringBuilder ();
623 while ((line = reader.ReadLine ()) != null) {
626 for (int i = 0; i < t; i++) {
629 if (c == '"' || c == '\'') {
632 for (i++; i < t; i++){
639 } else if (c == ' ') {
640 if (arg.Length > 0) {
641 yield return arg.ToString ();
647 if (arg.Length > 0) {
648 yield return arg.ToString ();
661 public class ResponseFileSource : ArgumentSource {
663 public override string[] GetNames ()
665 return new string[]{"@file"};
668 public override string Description {
669 get {return "Read response file for more options.";}
672 public override bool GetArguments (string value, out IEnumerable<string> replacement)
674 if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
678 replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
687 public class OptionException : Exception {
688 private string option;
690 public OptionException ()
694 public OptionException (string message, string optionName)
697 this.option = optionName;
700 public OptionException (string message, string optionName, Exception innerException)
701 : base (message, innerException)
703 this.option = optionName;
707 protected OptionException (SerializationInfo info, StreamingContext context)
708 : base (info, context)
710 this.option = info.GetString ("OptionName");
714 public string OptionName {
715 get {return this.option;}
719 #pragma warning disable 618 // SecurityPermissionAttribute is obsolete
720 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
721 #pragma warning restore 618
722 public override void GetObjectData (SerializationInfo info, StreamingContext context)
724 base.GetObjectData (info, context);
725 info.AddValue ("OptionName", option);
730 public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
732 public class OptionSet : KeyedCollection<string, Option>
735 : this (delegate (string f) {return f;})
739 public OptionSet (MessageLocalizerConverter localizer)
741 this.localizer = localizer;
742 this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
745 MessageLocalizerConverter localizer;
747 public MessageLocalizerConverter MessageLocalizer {
748 get {return localizer;}
751 List<ArgumentSource> sources = new List<ArgumentSource> ();
752 ReadOnlyCollection<ArgumentSource> roSources;
754 public ReadOnlyCollection<ArgumentSource> ArgumentSources {
755 get {return roSources;}
759 protected override string GetKeyForItem (Option item)
762 throw new ArgumentNullException ("option");
763 if (item.Names != null && item.Names.Length > 0)
764 return item.Names [0];
765 // This should never happen, as it's invalid for Option to be
766 // constructed w/o any names.
767 throw new InvalidOperationException ("Option has no names!");
770 [Obsolete ("Use KeyedCollection.this[string]")]
771 protected Option GetOptionForName (string option)
774 throw new ArgumentNullException ("option");
776 return base [option];
778 catch (KeyNotFoundException) {
783 protected override void InsertItem (int index, Option item)
785 base.InsertItem (index, item);
789 protected override void RemoveItem (int index)
791 Option p = Items [index];
792 base.RemoveItem (index);
793 // KeyedCollection.RemoveItem() handles the 0th item
794 for (int i = 1; i < p.Names.Length; ++i) {
795 Dictionary.Remove (p.Names [i]);
799 protected override void SetItem (int index, Option item)
801 base.SetItem (index, item);
805 private void AddImpl (Option option)
808 throw new ArgumentNullException ("option");
809 List<string> added = new List<string> (option.Names.Length);
811 // KeyedCollection.InsertItem/SetItem handle the 0th name.
812 for (int i = 1; i < option.Names.Length; ++i) {
813 Dictionary.Add (option.Names [i], option);
814 added.Add (option.Names [i]);
818 foreach (string name in added)
819 Dictionary.Remove (name);
824 public OptionSet Add (string header)
827 throw new ArgumentNullException ("header");
828 Add (new Category (header));
832 internal sealed class Category : Option {
834 // Prototype starts with '=' because this is an invalid prototype
835 // (see Option.ParsePrototype(), and thus it'll prevent Category
836 // instances from being accidentally used as normal options.
837 public Category (string description)
838 : base ("=:Category:= " + description, description)
842 protected override void OnParseComplete (OptionContext c)
844 throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
849 public new OptionSet Add (Option option)
855 sealed class ActionOption : Option {
856 Action<OptionValueCollection> action;
858 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
859 : this (prototype, description, count, action, false)
863 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden)
864 : base (prototype, description, count, hidden)
867 throw new ArgumentNullException ("action");
868 this.action = action;
871 protected override void OnParseComplete (OptionContext c)
873 action (c.OptionValues);
877 public OptionSet Add (string prototype, Action<string> action)
879 return Add (prototype, null, action);
882 public OptionSet Add (string prototype, string description, Action<string> action)
884 return Add (prototype, description, action, false);
887 public OptionSet Add (string prototype, string description, Action<string> action, bool hidden)
890 throw new ArgumentNullException ("action");
891 Option p = new ActionOption (prototype, description, 1,
892 delegate (OptionValueCollection v) { action (v [0]); }, hidden);
897 public OptionSet Add (string prototype, OptionAction<string, string> action)
899 return Add (prototype, null, action);
902 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
904 return Add (prototype, description, action, false);
907 public OptionSet Add (string prototype, string description, OptionAction<string, string> action, bool hidden) {
909 throw new ArgumentNullException ("action");
910 Option p = new ActionOption (prototype, description, 2,
911 delegate (OptionValueCollection v) {action (v [0], v [1]);}, hidden);
916 sealed class ActionOption<T> : Option {
919 public ActionOption (string prototype, string description, Action<T> action)
920 : base (prototype, description, 1)
923 throw new ArgumentNullException ("action");
924 this.action = action;
927 protected override void OnParseComplete (OptionContext c)
929 action (Parse<T> (c.OptionValues [0], c));
933 sealed class ActionOption<TKey, TValue> : Option {
934 OptionAction<TKey, TValue> action;
936 public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
937 : base (prototype, description, 2)
940 throw new ArgumentNullException ("action");
941 this.action = action;
944 protected override void OnParseComplete (OptionContext c)
947 Parse<TKey> (c.OptionValues [0], c),
948 Parse<TValue> (c.OptionValues [1], c));
952 public OptionSet Add<T> (string prototype, Action<T> action)
954 return Add (prototype, null, action);
957 public OptionSet Add<T> (string prototype, string description, Action<T> action)
959 return Add (new ActionOption<T> (prototype, description, action));
962 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
964 return Add (prototype, null, action);
967 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
969 return Add (new ActionOption<TKey, TValue> (prototype, description, action));
972 public OptionSet Add (ArgumentSource source)
975 throw new ArgumentNullException ("source");
976 sources.Add (source);
980 protected virtual OptionContext CreateOptionContext ()
982 return new OptionContext (this);
985 public List<string> Parse (IEnumerable<string> arguments)
987 if (arguments == null)
988 throw new ArgumentNullException ("arguments");
989 OptionContext c = CreateOptionContext ();
992 List<string> unprocessed = new List<string> ();
993 Option def = Contains ("<>") ? this ["<>"] : null;
994 ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
995 foreach (string argument in ae) {
997 if (argument == "--") {
1002 Unprocessed (unprocessed, def, c, argument);
1005 if (AddSource (ae, argument))
1007 if (!Parse (argument, c))
1008 Unprocessed (unprocessed, def, c, argument);
1010 if (c.Option != null)
1011 c.Option.Invoke (c);
1015 class ArgumentEnumerator : IEnumerable<string> {
1016 List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
1018 public ArgumentEnumerator (IEnumerable<string> arguments)
1020 sources.Add (arguments.GetEnumerator ());
1023 public void Add (IEnumerable<string> arguments)
1025 sources.Add (arguments.GetEnumerator ());
1028 public IEnumerator<string> GetEnumerator ()
1031 IEnumerator<string> c = sources [sources.Count-1];
1033 yield return c.Current;
1036 sources.RemoveAt (sources.Count-1);
1038 } while (sources.Count > 0);
1041 IEnumerator IEnumerable.GetEnumerator ()
1043 return GetEnumerator ();
1047 bool AddSource (ArgumentEnumerator ae, string argument)
1049 foreach (ArgumentSource source in sources) {
1050 IEnumerable<string> replacement;
1051 if (!source.GetArguments (argument, out replacement))
1053 ae.Add (replacement);
1059 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
1062 extra.Add (argument);
1065 c.OptionValues.Add (argument);
1067 c.Option.Invoke (c);
1071 private readonly Regex ValueOption = new Regex (
1072 @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
1074 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
1076 if (argument == null)
1077 throw new ArgumentNullException ("argument");
1079 flag = name = sep = value = null;
1080 Match m = ValueOption.Match (argument);
1084 flag = m.Groups ["flag"].Value;
1085 name = m.Groups ["name"].Value;
1086 if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
1087 sep = m.Groups ["sep"].Value;
1088 value = m.Groups ["value"].Value;
1093 protected virtual bool Parse (string argument, OptionContext c)
1095 if (c.Option != null) {
1096 ParseValue (argument, c);
1101 if (!GetOptionParts (argument, out f, out n, out s, out v))
1107 c.OptionName = f + n;
1109 switch (p.OptionValueType) {
1110 case OptionValueType.None:
1111 c.OptionValues.Add (n);
1112 c.Option.Invoke (c);
1114 case OptionValueType.Optional:
1115 case OptionValueType.Required:
1121 // no match; is it a bool option?
1122 if (ParseBool (argument, n, c))
1124 // is it a bundled option?
1125 if (ParseBundledValue (f, string.Concat (n + s + v), c))
1131 private void ParseValue (string option, OptionContext c)
1134 foreach (string o in c.Option.ValueSeparators != null
1135 ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
1136 : new string[]{option}) {
1137 c.OptionValues.Add (o);
1139 if (c.OptionValues.Count == c.Option.MaxValueCount ||
1140 c.Option.OptionValueType == OptionValueType.Optional)
1141 c.Option.Invoke (c);
1142 else if (c.OptionValues.Count > c.Option.MaxValueCount) {
1143 throw new OptionException (localizer (string.Format (
1144 "Error: Found {0} option values when expecting {1}.",
1145 c.OptionValues.Count, c.Option.MaxValueCount)),
1150 private bool ParseBool (string option, string n, OptionContext c)
1154 if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
1155 Contains ((rn = n.Substring (0, n.Length-1)))) {
1157 string v = n [n.Length-1] == '+' ? option : null;
1158 c.OptionName = option;
1160 c.OptionValues.Add (v);
1167 private bool ParseBundledValue (string f, string n, OptionContext c)
1171 for (int i = 0; i < n.Length; ++i) {
1173 string opt = f + n [i].ToString ();
1174 string rn = n [i].ToString ();
1175 if (!Contains (rn)) {
1178 throw new OptionException (string.Format (localizer (
1179 "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null);
1182 switch (p.OptionValueType) {
1183 case OptionValueType.None:
1184 Invoke (c, opt, n, p);
1186 case OptionValueType.Optional:
1187 case OptionValueType.Required: {
1188 string v = n.Substring (i+1);
1191 ParseValue (v.Length != 0 ? v : null, c);
1195 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
1201 private static void Invoke (OptionContext c, string name, string value, Option option)
1203 c.OptionName = name;
1205 c.OptionValues.Add (value);
1209 private const int OptionWidth = 29;
1210 private const int Description_FirstWidth = 80 - OptionWidth;
1211 private const int Description_RemWidth = 80 - OptionWidth - 2;
1213 public void WriteOptionDescriptions (TextWriter o)
1215 foreach (Option p in this) {
1221 Category c = p as Category;
1223 WriteDescription (o, p.Description, "", 80, 80);
1227 if (!WriteOptionPrototype (o, p, ref written))
1230 if (written < OptionWidth)
1231 o.Write (new string (' ', OptionWidth - written));
1234 o.Write (new string (' ', OptionWidth));
1237 WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
1238 Description_FirstWidth, Description_RemWidth);
1241 foreach (ArgumentSource s in sources) {
1242 string[] names = s.GetNames ();
1243 if (names == null || names.Length == 0)
1248 Write (o, ref written, " ");
1249 Write (o, ref written, names [0]);
1250 for (int i = 1; i < names.Length; ++i) {
1251 Write (o, ref written, ", ");
1252 Write (o, ref written, names [i]);
1255 if (written < OptionWidth)
1256 o.Write (new string (' ', OptionWidth - written));
1259 o.Write (new string (' ', OptionWidth));
1262 WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
1263 Description_FirstWidth, Description_RemWidth);
1267 void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
1269 bool indent = false;
1270 foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
1278 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
1280 string[] names = p.Names;
1282 int i = GetNextOptionIndex (names, 0);
1283 if (i == names.Length)
1286 if (names [i].Length == 1) {
1287 Write (o, ref written, " -");
1288 Write (o, ref written, names [0]);
1291 Write (o, ref written, " --");
1292 Write (o, ref written, names [0]);
1295 for ( i = GetNextOptionIndex (names, i+1);
1296 i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1297 Write (o, ref written, ", ");
1298 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1299 Write (o, ref written, names [i]);
1302 if (p.OptionValueType == OptionValueType.Optional ||
1303 p.OptionValueType == OptionValueType.Required) {
1304 if (p.OptionValueType == OptionValueType.Optional) {
1305 Write (o, ref written, localizer ("["));
1307 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1308 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
1309 ? p.ValueSeparators [0]
1311 for (int c = 1; c < p.MaxValueCount; ++c) {
1312 Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1314 if (p.OptionValueType == OptionValueType.Optional) {
1315 Write (o, ref written, localizer ("]"));
1321 static int GetNextOptionIndex (string[] names, int i)
1323 while (i < names.Length && names [i] == "<>") {
1329 static void Write (TextWriter o, ref int n, string s)
1335 private static string GetArgumentName (int index, int maxIndex, string description)
1337 if (description == null)
1338 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1341 nameStart = new string[]{"{0:", "{"};
1343 nameStart = new string[]{"{" + index + ":"};
1344 for (int i = 0; i < nameStart.Length; ++i) {
1347 start = description.IndexOf (nameStart [i], j);
1348 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1351 int end = description.IndexOf ("}", start);
1354 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1356 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1359 private static string GetDescription (string description)
1361 if (description == null)
1362 return string.Empty;
1363 StringBuilder sb = new StringBuilder (description.Length);
1365 for (int i = 0; i < description.Length; ++i) {
1366 switch (description [i]) {
1377 if ((i+1) == description.Length || description [i+1] != '}')
1378 throw new InvalidOperationException ("Invalid option description: " + description);
1383 sb.Append (description.Substring (start, i - start));
1394 sb.Append (description [i]);
1398 return sb.ToString ();
1401 private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
1403 return StringCoda.WrappedLines (description, firstWidth, remWidth);