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 t = (T) Convert.ChangeType (value, targetType);
482 TypeConverter conv = TypeDescriptor.GetConverter (targetType);
483 t = (T) conv.ConvertFromString (value);
487 catch (Exception e) {
488 throw new OptionException (
490 c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
491 value, targetType.Name, c.OptionName),
497 internal string[] Names {get {return names;}}
498 internal string[] ValueSeparators {get {return separators;}}
500 static readonly char[] NameTerminator = new char[]{'=', ':'};
502 private OptionValueType ParsePrototype ()
505 List<string> seps = new List<string> ();
506 for (int i = 0; i < names.Length; ++i) {
507 string name = names [i];
508 if (name.Length == 0)
509 throw new ArgumentException ("Empty option names are not supported.", "prototype");
511 int end = name.IndexOfAny (NameTerminator);
514 names [i] = name.Substring (0, end);
515 if (type == '\0' || type == name [end])
518 throw new ArgumentException (
519 string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
521 AddSeparators (name, end, seps);
525 return OptionValueType.None;
527 if (count <= 1 && seps.Count != 0)
528 throw new ArgumentException (
529 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
533 this.separators = new string[]{":", "="};
534 else if (seps.Count == 1 && seps [0].Length == 0)
535 this.separators = null;
537 this.separators = seps.ToArray ();
540 return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
543 private static void AddSeparators (string name, int end, ICollection<string> seps)
546 for (int i = end+1; i < name.Length; ++i) {
550 throw new ArgumentException (
551 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
557 throw new ArgumentException (
558 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
560 seps.Add (name.Substring (start, i-start));
565 seps.Add (name [i].ToString ());
570 throw new ArgumentException (
571 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
575 public void Invoke (OptionContext c)
580 c.OptionValues.Clear ();
583 protected abstract void OnParseComplete (OptionContext c);
585 public override string ToString ()
591 public abstract class ArgumentSource {
593 protected ArgumentSource ()
597 public abstract string[] GetNames ();
598 public abstract string Description { get; }
599 public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
602 public static IEnumerable<string> GetArgumentsFromFile (string file)
604 return GetArguments (File.OpenText (file), true);
608 public static IEnumerable<string> GetArguments (TextReader reader)
610 return GetArguments (reader, false);
613 // Cribbed from mcs/driver.cs:LoadArgs(string)
614 static IEnumerable<string> GetArguments (TextReader reader, bool close)
617 StringBuilder arg = new StringBuilder ();
620 while ((line = reader.ReadLine ()) != null) {
623 for (int i = 0; i < t; i++) {
626 if (c == '"' || c == '\'') {
629 for (i++; i < t; i++){
636 } else if (c == ' ') {
637 if (arg.Length > 0) {
638 yield return arg.ToString ();
644 if (arg.Length > 0) {
645 yield return arg.ToString ();
658 public class ResponseFileSource : ArgumentSource {
660 public override string[] GetNames ()
662 return new string[]{"@file"};
665 public override string Description {
666 get {return "Read response file for more options.";}
669 public override bool GetArguments (string value, out IEnumerable<string> replacement)
671 if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
675 replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
684 public class OptionException : Exception {
685 private string option;
687 public OptionException ()
691 public OptionException (string message, string optionName)
694 this.option = optionName;
697 public OptionException (string message, string optionName, Exception innerException)
698 : base (message, innerException)
700 this.option = optionName;
704 protected OptionException (SerializationInfo info, StreamingContext context)
705 : base (info, context)
707 this.option = info.GetString ("OptionName");
711 public string OptionName {
712 get {return this.option;}
716 #pragma warning disable 618 // SecurityPermissionAttribute is obsolete
717 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
718 #pragma warning restore 618
719 public override void GetObjectData (SerializationInfo info, StreamingContext context)
721 base.GetObjectData (info, context);
722 info.AddValue ("OptionName", option);
727 public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
729 public class OptionSet : KeyedCollection<string, Option>
732 : this (delegate (string f) {return f;})
736 public OptionSet (MessageLocalizerConverter localizer)
738 this.localizer = localizer;
739 this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
742 MessageLocalizerConverter localizer;
744 public MessageLocalizerConverter MessageLocalizer {
745 get {return localizer;}
748 List<ArgumentSource> sources = new List<ArgumentSource> ();
749 ReadOnlyCollection<ArgumentSource> roSources;
751 public ReadOnlyCollection<ArgumentSource> ArgumentSources {
752 get {return roSources;}
756 protected override string GetKeyForItem (Option item)
759 throw new ArgumentNullException ("option");
760 if (item.Names != null && item.Names.Length > 0)
761 return item.Names [0];
762 // This should never happen, as it's invalid for Option to be
763 // constructed w/o any names.
764 throw new InvalidOperationException ("Option has no names!");
767 [Obsolete ("Use KeyedCollection.this[string]")]
768 protected Option GetOptionForName (string option)
771 throw new ArgumentNullException ("option");
773 return base [option];
775 catch (KeyNotFoundException) {
780 protected override void InsertItem (int index, Option item)
782 base.InsertItem (index, item);
786 protected override void RemoveItem (int index)
788 Option p = Items [index];
789 base.RemoveItem (index);
790 // KeyedCollection.RemoveItem() handles the 0th item
791 for (int i = 1; i < p.Names.Length; ++i) {
792 Dictionary.Remove (p.Names [i]);
796 protected override void SetItem (int index, Option item)
798 base.SetItem (index, item);
802 private void AddImpl (Option option)
805 throw new ArgumentNullException ("option");
806 List<string> added = new List<string> (option.Names.Length);
808 // KeyedCollection.InsertItem/SetItem handle the 0th name.
809 for (int i = 1; i < option.Names.Length; ++i) {
810 Dictionary.Add (option.Names [i], option);
811 added.Add (option.Names [i]);
815 foreach (string name in added)
816 Dictionary.Remove (name);
821 public OptionSet Add (string header)
824 throw new ArgumentNullException ("header");
825 Add (new Category (header));
829 internal sealed class Category : Option {
831 // Prototype starts with '=' because this is an invalid prototype
832 // (see Option.ParsePrototype(), and thus it'll prevent Category
833 // instances from being accidentally used as normal options.
834 public Category (string description)
835 : base ("=:Category:= " + description, description)
839 protected override void OnParseComplete (OptionContext c)
841 throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
846 public new OptionSet Add (Option option)
852 sealed class ActionOption : Option {
853 Action<OptionValueCollection> action;
855 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
856 : this (prototype, description, count, action, false)
860 public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden)
861 : base (prototype, description, count, hidden)
864 throw new ArgumentNullException ("action");
865 this.action = action;
868 protected override void OnParseComplete (OptionContext c)
870 action (c.OptionValues);
874 public OptionSet Add (string prototype, Action<string> action)
876 return Add (prototype, null, action);
879 public OptionSet Add (string prototype, string description, Action<string> action)
881 return Add (prototype, description, action, false);
884 public OptionSet Add (string prototype, string description, Action<string> action, bool hidden)
887 throw new ArgumentNullException ("action");
888 Option p = new ActionOption (prototype, description, 1,
889 delegate (OptionValueCollection v) { action (v [0]); }, hidden);
894 public OptionSet Add (string prototype, OptionAction<string, string> action)
896 return Add (prototype, null, action);
899 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
901 return Add (prototype, description, action, false);
904 public OptionSet Add (string prototype, string description, OptionAction<string, string> action, bool hidden) {
906 throw new ArgumentNullException ("action");
907 Option p = new ActionOption (prototype, description, 2,
908 delegate (OptionValueCollection v) {action (v [0], v [1]);}, hidden);
913 sealed class ActionOption<T> : Option {
916 public ActionOption (string prototype, string description, Action<T> action)
917 : base (prototype, description, 1)
920 throw new ArgumentNullException ("action");
921 this.action = action;
924 protected override void OnParseComplete (OptionContext c)
926 action (Parse<T> (c.OptionValues [0], c));
930 sealed class ActionOption<TKey, TValue> : Option {
931 OptionAction<TKey, TValue> action;
933 public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
934 : base (prototype, description, 2)
937 throw new ArgumentNullException ("action");
938 this.action = action;
941 protected override void OnParseComplete (OptionContext c)
944 Parse<TKey> (c.OptionValues [0], c),
945 Parse<TValue> (c.OptionValues [1], c));
949 public OptionSet Add<T> (string prototype, Action<T> action)
951 return Add (prototype, null, action);
954 public OptionSet Add<T> (string prototype, string description, Action<T> action)
956 return Add (new ActionOption<T> (prototype, description, action));
959 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
961 return Add (prototype, null, action);
964 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
966 return Add (new ActionOption<TKey, TValue> (prototype, description, action));
969 public OptionSet Add (ArgumentSource source)
972 throw new ArgumentNullException ("source");
973 sources.Add (source);
977 protected virtual OptionContext CreateOptionContext ()
979 return new OptionContext (this);
982 public List<string> Parse (IEnumerable<string> arguments)
984 if (arguments == null)
985 throw new ArgumentNullException ("arguments");
986 OptionContext c = CreateOptionContext ();
989 List<string> unprocessed = new List<string> ();
990 Option def = Contains ("<>") ? this ["<>"] : null;
991 ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
992 foreach (string argument in ae) {
994 if (argument == "--") {
999 Unprocessed (unprocessed, def, c, argument);
1002 if (AddSource (ae, argument))
1004 if (!Parse (argument, c))
1005 Unprocessed (unprocessed, def, c, argument);
1007 if (c.Option != null)
1008 c.Option.Invoke (c);
1012 class ArgumentEnumerator : IEnumerable<string> {
1013 List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
1015 public ArgumentEnumerator (IEnumerable<string> arguments)
1017 sources.Add (arguments.GetEnumerator ());
1020 public void Add (IEnumerable<string> arguments)
1022 sources.Add (arguments.GetEnumerator ());
1025 public IEnumerator<string> GetEnumerator ()
1028 IEnumerator<string> c = sources [sources.Count-1];
1030 yield return c.Current;
1033 sources.RemoveAt (sources.Count-1);
1035 } while (sources.Count > 0);
1038 IEnumerator IEnumerable.GetEnumerator ()
1040 return GetEnumerator ();
1044 bool AddSource (ArgumentEnumerator ae, string argument)
1046 foreach (ArgumentSource source in sources) {
1047 IEnumerable<string> replacement;
1048 if (!source.GetArguments (argument, out replacement))
1050 ae.Add (replacement);
1056 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
1059 extra.Add (argument);
1062 c.OptionValues.Add (argument);
1064 c.Option.Invoke (c);
1068 private readonly Regex ValueOption = new Regex (
1069 @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
1071 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
1073 if (argument == null)
1074 throw new ArgumentNullException ("argument");
1076 flag = name = sep = value = null;
1077 Match m = ValueOption.Match (argument);
1081 flag = m.Groups ["flag"].Value;
1082 name = m.Groups ["name"].Value;
1083 if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
1084 sep = m.Groups ["sep"].Value;
1085 value = m.Groups ["value"].Value;
1090 protected virtual bool Parse (string argument, OptionContext c)
1092 if (c.Option != null) {
1093 ParseValue (argument, c);
1098 if (!GetOptionParts (argument, out f, out n, out s, out v))
1104 c.OptionName = f + n;
1106 switch (p.OptionValueType) {
1107 case OptionValueType.None:
1108 c.OptionValues.Add (n);
1109 c.Option.Invoke (c);
1111 case OptionValueType.Optional:
1112 case OptionValueType.Required:
1118 // no match; is it a bool option?
1119 if (ParseBool (argument, n, c))
1121 // is it a bundled option?
1122 if (ParseBundledValue (f, string.Concat (n + s + v), c))
1128 private void ParseValue (string option, OptionContext c)
1131 foreach (string o in c.Option.ValueSeparators != null
1132 ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
1133 : new string[]{option}) {
1134 c.OptionValues.Add (o);
1136 if (c.OptionValues.Count == c.Option.MaxValueCount ||
1137 c.Option.OptionValueType == OptionValueType.Optional)
1138 c.Option.Invoke (c);
1139 else if (c.OptionValues.Count > c.Option.MaxValueCount) {
1140 throw new OptionException (localizer (string.Format (
1141 "Error: Found {0} option values when expecting {1}.",
1142 c.OptionValues.Count, c.Option.MaxValueCount)),
1147 private bool ParseBool (string option, string n, OptionContext c)
1151 if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
1152 Contains ((rn = n.Substring (0, n.Length-1)))) {
1154 string v = n [n.Length-1] == '+' ? option : null;
1155 c.OptionName = option;
1157 c.OptionValues.Add (v);
1164 private bool ParseBundledValue (string f, string n, OptionContext c)
1168 for (int i = 0; i < n.Length; ++i) {
1170 string opt = f + n [i].ToString ();
1171 string rn = n [i].ToString ();
1172 if (!Contains (rn)) {
1175 throw new OptionException (string.Format (localizer (
1176 "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null);
1179 switch (p.OptionValueType) {
1180 case OptionValueType.None:
1181 Invoke (c, opt, n, p);
1183 case OptionValueType.Optional:
1184 case OptionValueType.Required: {
1185 string v = n.Substring (i+1);
1188 ParseValue (v.Length != 0 ? v : null, c);
1192 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
1198 private static void Invoke (OptionContext c, string name, string value, Option option)
1200 c.OptionName = name;
1202 c.OptionValues.Add (value);
1206 private const int OptionWidth = 29;
1207 private const int Description_FirstWidth = 80 - OptionWidth;
1208 private const int Description_RemWidth = 80 - OptionWidth - 2;
1210 public void WriteOptionDescriptions (TextWriter o)
1212 foreach (Option p in this) {
1218 Category c = p as Category;
1220 WriteDescription (o, p.Description, "", 80, 80);
1224 if (!WriteOptionPrototype (o, p, ref written))
1227 if (written < OptionWidth)
1228 o.Write (new string (' ', OptionWidth - written));
1231 o.Write (new string (' ', OptionWidth));
1234 WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
1235 Description_FirstWidth, Description_RemWidth);
1238 foreach (ArgumentSource s in sources) {
1239 string[] names = s.GetNames ();
1240 if (names == null || names.Length == 0)
1245 Write (o, ref written, " ");
1246 Write (o, ref written, names [0]);
1247 for (int i = 1; i < names.Length; ++i) {
1248 Write (o, ref written, ", ");
1249 Write (o, ref written, names [i]);
1252 if (written < OptionWidth)
1253 o.Write (new string (' ', OptionWidth - written));
1256 o.Write (new string (' ', OptionWidth));
1259 WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
1260 Description_FirstWidth, Description_RemWidth);
1264 void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
1266 bool indent = false;
1267 foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
1275 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
1277 string[] names = p.Names;
1279 int i = GetNextOptionIndex (names, 0);
1280 if (i == names.Length)
1283 if (names [i].Length == 1) {
1284 Write (o, ref written, " -");
1285 Write (o, ref written, names [0]);
1288 Write (o, ref written, " --");
1289 Write (o, ref written, names [0]);
1292 for ( i = GetNextOptionIndex (names, i+1);
1293 i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1294 Write (o, ref written, ", ");
1295 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1296 Write (o, ref written, names [i]);
1299 if (p.OptionValueType == OptionValueType.Optional ||
1300 p.OptionValueType == OptionValueType.Required) {
1301 if (p.OptionValueType == OptionValueType.Optional) {
1302 Write (o, ref written, localizer ("["));
1304 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1305 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
1306 ? p.ValueSeparators [0]
1308 for (int c = 1; c < p.MaxValueCount; ++c) {
1309 Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1311 if (p.OptionValueType == OptionValueType.Optional) {
1312 Write (o, ref written, localizer ("]"));
1318 static int GetNextOptionIndex (string[] names, int i)
1320 while (i < names.Length && names [i] == "<>") {
1326 static void Write (TextWriter o, ref int n, string s)
1332 private static string GetArgumentName (int index, int maxIndex, string description)
1334 if (description == null)
1335 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1338 nameStart = new string[]{"{0:", "{"};
1340 nameStart = new string[]{"{" + index + ":"};
1341 for (int i = 0; i < nameStart.Length; ++i) {
1344 start = description.IndexOf (nameStart [i], j);
1345 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1348 int end = description.IndexOf ("}", start);
1351 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1353 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1356 private static string GetDescription (string description)
1358 if (description == null)
1359 return string.Empty;
1360 StringBuilder sb = new StringBuilder (description.Length);
1362 for (int i = 0; i < description.Length; ++i) {
1363 switch (description [i]) {
1374 if ((i+1) == description.Length || description [i+1] != '}')
1375 throw new InvalidOperationException ("Invalid option description: " + description);
1380 sb.Append (description.Substring (start, i - start));
1391 sb.Append (description [i]);
1395 return sb.ToString ();
1398 private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
1400 return StringCoda.WrappedLines (description, firstWidth, remWidth);