[Mono.Options] Add Mono.Options.Command, .CommandSet
[mono.git] / mcs / class / Mono.Options / Mono.Options / Options.cs
1 //
2 // Options.cs
3 //
4 // Authors:
5 //  Jonathan Pryor <jpryor@novell.com>, <Jonathan.Pryor@microsoft.com>
6 //  Federico Di Gregorio <fog@initd.org>
7 //  Rolf Bjarne Kvinge <rolf@xamarin.com>
8 //
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)
12 // Copyright (C) 2017 Microsoft Corporation (http://www.microsoft.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 // Compile With:
35 //   mcs -debug+ -r:System.Core Options.cs -o:Mono.Options.dll
36 //   mcs -debug+ -d:LINQ -r:System.Core Options.cs -o:Mono.Options.dll
37 //
38 // The LINQ version just changes the implementation of
39 // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
40
41 //
42 // A Getopt::Long-inspired option parsing library for C#.
43 //
44 // Mono.Options.OptionSet is built upon a key/value table, where the
45 // key is a option format string and the value is a delegate that is 
46 // invoked when the format string is matched.
47 //
48 // Option format strings:
49 //  Regex-like BNF Grammar: 
50 //    name: .+
51 //    type: [=:]
52 //    sep: ( [^{}]+ | '{' .+ '}' )?
53 //    aliases: ( name type sep ) ( '|' name type sep )*
54 // 
55 // Each '|'-delimited name is an alias for the associated action.  If the
56 // format string ends in a '=', it has a required value.  If the format
57 // string ends in a ':', it has an optional value.  If neither '=' or ':'
58 // is present, no value is supported.  `=' or `:' need only be defined on one
59 // alias, but if they are provided on more than one they must be consistent.
60 //
61 // Each alias portion may also end with a "key/value separator", which is used
62 // to split option values if the option accepts > 1 value.  If not specified,
63 // it defaults to '=' and ':'.  If specified, it can be any character except
64 // '{' and '}' OR the *string* between '{' and '}'.  If no separator should be
65 // used (i.e. the separate values should be distinct arguments), then "{}"
66 // should be used as the separator.
67 //
68 // Options are extracted either from the current option by looking for
69 // the option name followed by an '=' or ':', or is taken from the
70 // following option IFF:
71 //  - The current option does not contain a '=' or a ':'
72 //  - The current option requires a value (i.e. not a Option type of ':')
73 //
74 // The `name' used in the option format string does NOT include any leading
75 // option indicator, such as '-', '--', or '/'.  All three of these are
76 // permitted/required on any named option.
77 //
78 // Option bundling is permitted so long as:
79 //   - '-' is used to start the option group
80 //   - all of the bundled options are a single character
81 //   - at most one of the bundled options accepts a value, and the value
82 //     provided starts from the next character to the end of the string.
83 //
84 // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
85 // as '-Dname=value'.
86 //
87 // Option processing is disabled by specifying "--".  All options after "--"
88 // are returned by OptionSet.Parse() unchanged and unprocessed.
89 //
90 // Unprocessed options are returned from OptionSet.Parse().
91 //
92 // Examples:
93 //  int verbose = 0;
94 //  OptionSet p = new OptionSet ()
95 //    .Add ("v", v => ++verbose)
96 //    .Add ("name=|value=", v => Console.WriteLine (v));
97 //  p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
98 //
99 // The above would parse the argument string array, and would invoke the
100 // lambda expression three times, setting `verbose' to 3 when complete.  
101 // It would also print out "A" and "B" to standard output.
102 // The returned array would contain the string "extra".
103 //
104 // C# 3.0 collection initializers are supported and encouraged:
105 //  var p = new OptionSet () {
106 //    { "h|?|help", v => ShowHelp () },
107 //  };
108 //
109 // System.ComponentModel.TypeConverter is also supported, allowing the use of
110 // custom data types in the callback type; TypeConverter.ConvertFromString()
111 // is used to convert the value option to an instance of the specified
112 // type:
113 //
114 //  var p = new OptionSet () {
115 //    { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
116 //  };
117 //
118 // Random other tidbits:
119 //  - Boolean options (those w/o '=' or ':' in the option format string)
120 //    are explicitly enabled if they are followed with '+', and explicitly
121 //    disabled if they are followed with '-':
122 //      string a = null;
123 //      var p = new OptionSet () {
124 //        { "a", s => a = s },
125 //      };
126 //      p.Parse (new string[]{"-a"});   // sets v != null
127 //      p.Parse (new string[]{"-a+"});  // sets v != null
128 //      p.Parse (new string[]{"-a-"});  // sets v == null
129 //
130
131 //
132 // Mono.Options.CommandSet allows easily having separate commands and
133 // associated command options, allowing creation of a *suite* along the
134 // lines of **git**(1), **svn**(1), etc.
135 //
136 // CommandSet allows intermixing plain text strings for `--help` output,
137 // Option values -- as supported by OptionSet -- and Command instances,
138 // which have a name, optional help text, and an optional OptionSet.
139 //
140 //  var suite = new CommandSet ("suite-name") {
141 //    // Use strings and option values, as with OptionSet
142 //    "usage: suite-name COMMAND [OPTIONS]+",
143 //    { "v:", "verbosity", (int? v) => Verbosity = v.HasValue ? v.Value : Verbosity+1 },
144 //    // Commands may also be specified
145 //    new Command ("command-name", "command help") {
146 //      Options = new OptionSet {/*...*/},
147 //      Run     = args => { /*...*/},
148 //    },
149 //    new MyCommandSubclass (),
150 //  };
151 //  return suite.Run (new string[]{...});
152 //
153 // CommandSet provides a `help` command, and forwards `help COMMAND`
154 // to the registered Command instance by invoking Command.Invoke()
155 // with `--help` as an option.
156 //
157
158 using System;
159 using System.Collections;
160 using System.Collections.Generic;
161 using System.Collections.ObjectModel;
162 using System.ComponentModel;
163 using System.Globalization;
164 using System.IO;
165 using System.Runtime.Serialization;
166 #if PCL
167 using System.Reflection;
168 #else
169 using System.Security.Permissions;
170 #endif
171 using System.Text;
172 using System.Text.RegularExpressions;
173
174 #if LINQ
175 using System.Linq;
176 #endif
177
178 #if TEST
179 using NDesk.Options;
180 #endif
181
182 #if PCL
183 using MessageLocalizerConverter = System.Func<string, string>;
184 #else
185 using MessageLocalizerConverter = System.Converter<string, string>;
186 #endif
187
188 #if NDESK_OPTIONS
189 namespace NDesk.Options
190 #else
191 namespace Mono.Options
192 #endif
193 {
194         static class StringCoda {
195
196                 public static IEnumerable<string> WrappedLines (string self, params int[] widths)
197                 {
198                         IEnumerable<int> w = widths;
199                         return WrappedLines (self, w);
200                 }
201
202                 public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
203                 {
204                         if (widths == null)
205                                 throw new ArgumentNullException ("widths");
206                         return CreateWrappedLinesIterator (self, widths);
207                 }
208
209                 private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
210                 {
211                         if (string.IsNullOrEmpty (self)) {
212                                 yield return string.Empty;
213                                 yield break;
214                         }
215                         using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
216                                 bool? hw = null;
217                                 int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
218                                 int start = 0, end;
219                                 do {
220                                         end = GetLineEnd (start, width, self);
221                                         char c = self [end-1];
222                                         if (char.IsWhiteSpace (c))
223                                                 --end;
224                                         bool needContinuation = end != self.Length && !IsEolChar (c);
225                                         string continuation = "";
226                                         if (needContinuation) {
227                                                 --end;
228                                                 continuation = "-";
229                                         }
230                                         string line = self.Substring (start, end - start) + continuation;
231                                         yield return line;
232                                         start = end;
233                                         if (char.IsWhiteSpace (c))
234                                                 ++start;
235                                         width = GetNextWidth (ewidths, width, ref hw);
236                                 } while (start < self.Length);
237                         }
238                 }
239
240                 private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
241                 {
242                         if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
243                                 curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
244                                 // '.' is any character, - is for a continuation
245                                 const string minWidth = ".-";
246                                 if (curWidth < minWidth.Length)
247                                         throw new ArgumentOutOfRangeException ("widths",
248                                                         string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
249                                 return curWidth;
250                         }
251                         // no more elements, use the last element.
252                         return curWidth;
253                 }
254
255                 private static bool IsEolChar (char c)
256                 {
257                         return !char.IsLetterOrDigit (c);
258                 }
259
260                 private static int GetLineEnd (int start, int length, string description)
261                 {
262                         int end = System.Math.Min (start + length, description.Length);
263                         int sep = -1;
264                         for (int i = start; i < end; ++i) {
265                                 if (description [i] == '\n')
266                                         return i+1;
267                                 if (IsEolChar (description [i]))
268                                         sep = i+1;
269                         }
270                         if (sep == -1 || end == description.Length)
271                                 return end;
272                         return sep;
273                 }
274         }
275
276         public class OptionValueCollection : IList, IList<string> {
277
278                 List<string> values = new List<string> ();
279                 OptionContext c;
280
281                 internal OptionValueCollection (OptionContext c)
282                 {
283                         this.c = c;
284                 }
285
286                 #region ICollection
287                 void ICollection.CopyTo (Array array, int index)  {(values as ICollection).CopyTo (array, index);}
288                 bool ICollection.IsSynchronized                   {get {return (values as ICollection).IsSynchronized;}}
289                 object ICollection.SyncRoot                       {get {return (values as ICollection).SyncRoot;}}
290                 #endregion
291
292                 #region ICollection<T>
293                 public void Add (string item)                       {values.Add (item);}
294                 public void Clear ()                                {values.Clear ();}
295                 public bool Contains (string item)                  {return values.Contains (item);}
296                 public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
297                 public bool Remove (string item)                    {return values.Remove (item);}
298                 public int Count                                    {get {return values.Count;}}
299                 public bool IsReadOnly                              {get {return false;}}
300                 #endregion
301
302                 #region IEnumerable
303                 IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
304                 #endregion
305
306                 #region IEnumerable<T>
307                 public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
308                 #endregion
309
310                 #region IList
311                 int IList.Add (object value)                {return (values as IList).Add (value);}
312                 bool IList.Contains (object value)          {return (values as IList).Contains (value);}
313                 int IList.IndexOf (object value)            {return (values as IList).IndexOf (value);}
314                 void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
315                 void IList.Remove (object value)            {(values as IList).Remove (value);}
316                 void IList.RemoveAt (int index)             {(values as IList).RemoveAt (index);}
317                 bool IList.IsFixedSize                      {get {return false;}}
318                 object IList.this [int index]               {get {return this [index];} set {(values as IList)[index] = value;}}
319                 #endregion
320
321                 #region IList<T>
322                 public int IndexOf (string item)            {return values.IndexOf (item);}
323                 public void Insert (int index, string item) {values.Insert (index, item);}
324                 public void RemoveAt (int index)            {values.RemoveAt (index);}
325
326                 private void AssertValid (int index)
327                 {
328                         if (c.Option == null)
329                                 throw new InvalidOperationException ("OptionContext.Option is null.");
330                         if (index >= c.Option.MaxValueCount)
331                                 throw new ArgumentOutOfRangeException ("index");
332                         if (c.Option.OptionValueType == OptionValueType.Required &&
333                                         index >= values.Count)
334                                 throw new OptionException (string.Format (
335                                                         c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), 
336                                                 c.OptionName);
337                 }
338
339                 public string this [int index] {
340                         get {
341                                 AssertValid (index);
342                                 return index >= values.Count ? null : values [index];
343                         }
344                         set {
345                                 values [index] = value;
346                         }
347                 }
348                 #endregion
349
350                 public List<string> ToList ()
351                 {
352                         return new List<string> (values);
353                 }
354
355                 public string[] ToArray ()
356                 {
357                         return values.ToArray ();
358                 }
359
360                 public override string ToString ()
361                 {
362                         return string.Join (", ", values.ToArray ());
363                 }
364         }
365
366         public class OptionContext {
367                 private Option                option;
368                 private string                name;
369                 private int                   index;
370                 private OptionSet             set;
371                 private OptionValueCollection c;
372
373                 public OptionContext (OptionSet set)
374                 {
375                         this.set = set;
376                         this.c   = new OptionValueCollection (this);
377                 }
378
379                 public Option Option {
380                         get {return option;}
381                         set {option = value;}
382                 }
383
384                 public string OptionName { 
385                         get {return name;}
386                         set {name = value;}
387                 }
388
389                 public int OptionIndex {
390                         get {return index;}
391                         set {index = value;}
392                 }
393
394                 public OptionSet OptionSet {
395                         get {return set;}
396                 }
397
398                 public OptionValueCollection OptionValues {
399                         get {return c;}
400                 }
401         }
402
403         public enum OptionValueType {
404                 None, 
405                 Optional,
406                 Required,
407         }
408
409         public abstract class Option {
410                 string prototype, description;
411                 string[] names;
412                 OptionValueType type;
413                 int count;
414                 string[] separators;
415                 bool hidden;
416
417                 protected Option (string prototype, string description)
418                         : this (prototype, description, 1, false)
419                 {
420                 }
421
422                 protected Option (string prototype, string description, int maxValueCount)
423                         : this (prototype, description, maxValueCount, false)
424                 {
425                 }
426
427                 protected Option (string prototype, string description, int maxValueCount, bool hidden)
428                 {
429                         if (prototype == null)
430                                 throw new ArgumentNullException ("prototype");
431                         if (prototype.Length == 0)
432                                 throw new ArgumentException ("Cannot be the empty string.", "prototype");
433                         if (maxValueCount < 0)
434                                 throw new ArgumentOutOfRangeException ("maxValueCount");
435
436                         this.prototype   = prototype;
437                         this.description = description;
438                         this.count       = maxValueCount;
439                         this.names       = (this is OptionSet.Category)
440                                 // append GetHashCode() so that "duplicate" categories have distinct
441                                 // names, e.g. adding multiple "" categories should be valid.
442                                 ? new[]{prototype + this.GetHashCode ()}
443                                 : prototype.Split ('|');
444
445                         if (this is OptionSet.Category || this is CommandOption)
446                                 return;
447
448                         this.type        = ParsePrototype ();
449                         this.hidden      = hidden;
450
451                         if (this.count == 0 && type != OptionValueType.None)
452                                 throw new ArgumentException (
453                                                 "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
454                                                         "OptionValueType.Optional.",
455                                                 "maxValueCount");
456                         if (this.type == OptionValueType.None && maxValueCount > 1)
457                                 throw new ArgumentException (
458                                                 string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
459                                                 "maxValueCount");
460                         if (Array.IndexOf (names, "<>") >= 0 && 
461                                         ((names.Length == 1 && this.type != OptionValueType.None) ||
462                                          (names.Length > 1 && this.MaxValueCount > 1)))
463                                 throw new ArgumentException (
464                                                 "The default option handler '<>' cannot require values.",
465                                                 "prototype");
466                 }
467
468                 public string           Prototype       {get {return prototype;}}
469                 public string           Description     {get {return description;}}
470                 public OptionValueType  OptionValueType {get {return type;}}
471                 public int              MaxValueCount   {get {return count;}}
472                 public bool             Hidden          {get {return hidden;}}
473
474                 public string[] GetNames ()
475                 {
476                         return (string[]) names.Clone ();
477                 }
478
479                 public string[] GetValueSeparators ()
480                 {
481                         if (separators == null)
482                                 return new string [0];
483                         return (string[]) separators.Clone ();
484                 }
485
486                 protected static T Parse<T> (string value, OptionContext c)
487                 {
488                         Type tt = typeof (T);
489 #if PCL
490                         TypeInfo ti = tt.GetTypeInfo ();
491 #else
492                         Type ti = tt;
493 #endif
494                         bool nullable = 
495                                 ti.IsValueType && 
496                                 ti.IsGenericType && 
497                                 !ti.IsGenericTypeDefinition && 
498                                 ti.GetGenericTypeDefinition () == typeof (Nullable<>);
499 #if PCL
500                         Type targetType = nullable ? tt.GenericTypeArguments [0] : tt;
501 #else
502                         Type targetType = nullable ? tt.GetGenericArguments () [0] : tt;
503 #endif
504                         T t = default (T);
505                         try {
506                                 if (value != null) {
507 #if PCL
508                                         if (targetType.GetTypeInfo ().IsEnum)
509                                                 t = (T) Enum.Parse (targetType, value, true);
510                                         else
511                                                 t = (T) Convert.ChangeType (value, targetType);
512 #else
513                                         TypeConverter conv = TypeDescriptor.GetConverter (targetType);
514                                         t = (T) conv.ConvertFromString (value);
515 #endif
516                                 }
517                         }
518                         catch (Exception e) {
519                                 throw new OptionException (
520                                                 string.Format (
521                                                         c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
522                                                         value, targetType.Name, c.OptionName),
523                                                 c.OptionName, e);
524                         }
525                         return t;
526                 }
527
528                 internal string[] Names           {get {return names;}}
529                 internal string[] ValueSeparators {get {return separators;}}
530
531                 static readonly char[] NameTerminator = new char[]{'=', ':'};
532
533                 private OptionValueType ParsePrototype ()
534                 {
535                         char type = '\0';
536                         List<string> seps = new List<string> ();
537                         for (int i = 0; i < names.Length; ++i) {
538                                 string name = names [i];
539                                 if (name.Length == 0)
540                                         throw new ArgumentException ("Empty option names are not supported.", "prototype");
541
542                                 int end = name.IndexOfAny (NameTerminator);
543                                 if (end == -1)
544                                         continue;
545                                 names [i] = name.Substring (0, end);
546                                 if (type == '\0' || type == name [end])
547                                         type = name [end];
548                                 else 
549                                         throw new ArgumentException (
550                                                         string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
551                                                         "prototype");
552                                 AddSeparators (name, end, seps);
553                         }
554
555                         if (type == '\0')
556                                 return OptionValueType.None;
557
558                         if (count <= 1 && seps.Count != 0)
559                                 throw new ArgumentException (
560                                                 string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
561                                                 "prototype");
562                         if (count > 1) {
563                                 if (seps.Count == 0)
564                                         this.separators = new string[]{":", "="};
565                                 else if (seps.Count == 1 && seps [0].Length == 0)
566                                         this.separators = null;
567                                 else
568                                         this.separators = seps.ToArray ();
569                         }
570
571                         return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
572                 }
573
574                 private static void AddSeparators (string name, int end, ICollection<string> seps)
575                 {
576                         int start = -1;
577                         for (int i = end+1; i < name.Length; ++i) {
578                                 switch (name [i]) {
579                                         case '{':
580                                                 if (start != -1)
581                                                         throw new ArgumentException (
582                                                                         string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
583                                                                         "prototype");
584                                                 start = i+1;
585                                                 break;
586                                         case '}':
587                                                 if (start == -1)
588                                                         throw new ArgumentException (
589                                                                         string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
590                                                                         "prototype");
591                                                 seps.Add (name.Substring (start, i-start));
592                                                 start = -1;
593                                                 break;
594                                         default:
595                                                 if (start == -1)
596                                                         seps.Add (name [i].ToString ());
597                                                 break;
598                                 }
599                         }
600                         if (start != -1)
601                                 throw new ArgumentException (
602                                                 string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
603                                                 "prototype");
604                 }
605
606                 public void Invoke (OptionContext c)
607                 {
608                         OnParseComplete (c);
609                         c.OptionName  = null;
610                         c.Option      = null;
611                         c.OptionValues.Clear ();
612                 }
613
614                 protected abstract void OnParseComplete (OptionContext c);
615
616                 internal void InvokeOnParseComplete (OptionContext c)
617                 {
618                         OnParseComplete (c);
619                 }
620
621                 public override string ToString ()
622                 {
623                         return Prototype;
624                 }
625         }
626
627         public abstract class ArgumentSource {
628
629                 protected ArgumentSource ()
630                 {
631                 }
632
633                 public abstract string[] GetNames ();
634                 public abstract string Description { get; }
635                 public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
636
637 #if !PCL
638                 public static IEnumerable<string> GetArgumentsFromFile (string file)
639                 {
640                         return GetArguments (File.OpenText (file), true);
641                 }
642 #endif
643
644                 public static IEnumerable<string> GetArguments (TextReader reader)
645                 {
646                         return GetArguments (reader, false);
647                 }
648
649                 // Cribbed from mcs/driver.cs:LoadArgs(string)
650                 static IEnumerable<string> GetArguments (TextReader reader, bool close)
651                 {
652                         try {
653                                 StringBuilder arg = new StringBuilder ();
654
655                                 string line;
656                                 while ((line = reader.ReadLine ()) != null) {
657                                         int t = line.Length;
658
659                                         for (int i = 0; i < t; i++) {
660                                                 char c = line [i];
661                                                 
662                                                 if (c == '"' || c == '\'') {
663                                                         char end = c;
664                                                         
665                                                         for (i++; i < t; i++){
666                                                                 c = line [i];
667
668                                                                 if (c == end)
669                                                                         break;
670                                                                 arg.Append (c);
671                                                         }
672                                                 } else if (c == ' ') {
673                                                         if (arg.Length > 0) {
674                                                                 yield return arg.ToString ();
675                                                                 arg.Length = 0;
676                                                         }
677                                                 } else
678                                                         arg.Append (c);
679                                         }
680                                         if (arg.Length > 0) {
681                                                 yield return arg.ToString ();
682                                                 arg.Length = 0;
683                                         }
684                                 }
685                         }
686                         finally {
687                                 if (close)
688                                         reader.Dispose ();
689                         }
690                 }
691         }
692
693 #if !PCL
694         public class ResponseFileSource : ArgumentSource {
695
696                 public override string[] GetNames ()
697                 {
698                         return new string[]{"@file"};
699                 }
700
701                 public override string Description {
702                         get {return "Read response file for more options.";}
703                 }
704
705                 public override bool GetArguments (string value, out IEnumerable<string> replacement)
706                 {
707                         if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
708                                 replacement = null;
709                                 return false;
710                         }
711                         replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
712                         return true;
713                 }
714         }
715 #endif
716
717 #if !PCL
718         [Serializable]
719 #endif
720         public class OptionException : Exception {
721                 private string option;
722
723                 public OptionException ()
724                 {
725                 }
726
727                 public OptionException (string message, string optionName)
728                         : base (message)
729                 {
730                         this.option = optionName;
731                 }
732
733                 public OptionException (string message, string optionName, Exception innerException)
734                         : base (message, innerException)
735                 {
736                         this.option = optionName;
737                 }
738
739 #if !PCL
740                 protected OptionException (SerializationInfo info, StreamingContext context)
741                         : base (info, context)
742                 {
743                         this.option = info.GetString ("OptionName");
744                 }
745 #endif
746
747                 public string OptionName {
748                         get {return this.option;}
749                 }
750
751 #if !PCL
752 #pragma warning disable 618 // SecurityPermissionAttribute is obsolete
753                 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
754 #pragma warning restore 618
755                 public override void GetObjectData (SerializationInfo info, StreamingContext context)
756                 {
757                         base.GetObjectData (info, context);
758                         info.AddValue ("OptionName", option);
759                 }
760 #endif
761         }
762
763         public delegate void OptionAction<TKey, TValue> (TKey key, TValue value);
764
765         public class OptionSet : KeyedCollection<string, Option>
766         {
767                 public OptionSet ()
768                         : this (null)
769                 {
770                 }
771
772                 public OptionSet (MessageLocalizerConverter localizer)
773                 {
774                         this.roSources = new ReadOnlyCollection<ArgumentSource> (sources);
775                         this.localizer = localizer;
776                         if (this.localizer == null) {
777                                 this.localizer = delegate (string f) {
778                                         return f;
779                                 };
780                         }
781                 }
782
783                 MessageLocalizerConverter localizer;
784
785                 public MessageLocalizerConverter MessageLocalizer {
786                         get {return localizer;}
787                         internal set {localizer = value;}
788                 }
789
790                 List<ArgumentSource> sources = new List<ArgumentSource> ();
791                 ReadOnlyCollection<ArgumentSource> roSources;
792
793                 public ReadOnlyCollection<ArgumentSource> ArgumentSources {
794                         get {return roSources;}
795                 }
796
797
798                 protected override string GetKeyForItem (Option item)
799                 {
800                         if (item == null)
801                                 throw new ArgumentNullException ("option");
802                         if (item.Names != null && item.Names.Length > 0)
803                                 return item.Names [0];
804                         // This should never happen, as it's invalid for Option to be
805                         // constructed w/o any names.
806                         throw new InvalidOperationException ("Option has no names!");
807                 }
808
809                 [Obsolete ("Use KeyedCollection.this[string]")]
810                 protected Option GetOptionForName (string option)
811                 {
812                         if (option == null)
813                                 throw new ArgumentNullException ("option");
814                         try {
815                                 return base [option];
816                         }
817                         catch (KeyNotFoundException) {
818                                 return null;
819                         }
820                 }
821
822                 protected override void InsertItem (int index, Option item)
823                 {
824                         base.InsertItem (index, item);
825                         AddImpl (item);
826                 }
827
828                 protected override void RemoveItem (int index)
829                 {
830                         Option p = Items [index];
831                         base.RemoveItem (index);
832                         // KeyedCollection.RemoveItem() handles the 0th item
833                         for (int i = 1; i < p.Names.Length; ++i) {
834                                 Dictionary.Remove (p.Names [i]);
835                         }
836                 }
837
838                 protected override void SetItem (int index, Option item)
839                 {
840                         base.SetItem (index, item);
841                         AddImpl (item);
842                 }
843
844                 private void AddImpl (Option option)
845                 {
846                         if (option == null)
847                                 throw new ArgumentNullException ("option");
848                         List<string> added = new List<string> (option.Names.Length);
849                         try {
850                                 // KeyedCollection.InsertItem/SetItem handle the 0th name.
851                                 for (int i = 1; i < option.Names.Length; ++i) {
852                                         Dictionary.Add (option.Names [i], option);
853                                         added.Add (option.Names [i]);
854                                 }
855                         }
856                         catch (Exception) {
857                                 foreach (string name in added)
858                                         Dictionary.Remove (name);
859                                 throw;
860                         }
861                 }
862
863                 public OptionSet Add (string header)
864                 {
865                         if (header == null)
866                                 throw new ArgumentNullException ("header");
867                         Add (new Category (header));
868                         return this;
869                 }
870
871                 internal sealed class Category : Option {
872
873                         // Prototype starts with '=' because this is an invalid prototype
874                         // (see Option.ParsePrototype(), and thus it'll prevent Category
875                         // instances from being accidentally used as normal options.
876                         public Category (string description)
877                                 : base ("=:Category:= " + description, description)
878                         {
879                         }
880
881                         protected override void OnParseComplete (OptionContext c)
882                         {
883                                 throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
884                         }
885                 }
886
887
888                 public new OptionSet Add (Option option)
889                 {
890                         base.Add (option);
891                         return this;
892                 }
893
894                 sealed class ActionOption : Option {
895                         Action<OptionValueCollection> action;
896
897                         public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
898                                 : this (prototype, description, count, action, false)
899                         {
900                         }
901
902                         public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden)
903                                 : base (prototype, description, count, hidden)
904                         {
905                                 if (action == null)
906                                         throw new ArgumentNullException ("action");
907                                 this.action = action;
908                         }
909
910                         protected override void OnParseComplete (OptionContext c)
911                         {
912                                 action (c.OptionValues);
913                         }
914                 }
915
916                 public OptionSet Add (string prototype, Action<string> action)
917                 {
918                         return Add (prototype, null, action);
919                 }
920
921                 public OptionSet Add (string prototype, string description, Action<string> action)
922                 {
923                         return Add (prototype, description, action, false);
924                 }
925
926                 public OptionSet Add (string prototype, string description, Action<string> action, bool hidden)
927                 {
928                         if (action == null)
929                                 throw new ArgumentNullException ("action");
930                         Option p = new ActionOption (prototype, description, 1, 
931                                         delegate (OptionValueCollection v) { action (v [0]); }, hidden);
932                         base.Add (p);
933                         return this;
934                 }
935
936                 public OptionSet Add (string prototype, OptionAction<string, string> action)
937                 {
938                         return Add (prototype, null, action);
939                 }
940
941                 public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
942                 {
943                         return Add (prototype, description, action, false);
944                 }
945
946                 public OptionSet Add (string prototype, string description, OptionAction<string, string> action, bool hidden)   {
947                         if (action == null)
948                                 throw new ArgumentNullException ("action");
949                         Option p = new ActionOption (prototype, description, 2, 
950                                         delegate (OptionValueCollection v) {action (v [0], v [1]);}, hidden);
951                         base.Add (p);
952                         return this;
953                 }
954
955                 sealed class ActionOption<T> : Option {
956                         Action<T> action;
957
958                         public ActionOption (string prototype, string description, Action<T> action)
959                                 : base (prototype, description, 1)
960                         {
961                                 if (action == null)
962                                         throw new ArgumentNullException ("action");
963                                 this.action = action;
964                         }
965
966                         protected override void OnParseComplete (OptionContext c)
967                         {
968                                 action (Parse<T> (c.OptionValues [0], c));
969                         }
970                 }
971
972                 sealed class ActionOption<TKey, TValue> : Option {
973                         OptionAction<TKey, TValue> action;
974
975                         public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
976                                 : base (prototype, description, 2)
977                         {
978                                 if (action == null)
979                                         throw new ArgumentNullException ("action");
980                                 this.action = action;
981                         }
982
983                         protected override void OnParseComplete (OptionContext c)
984                         {
985                                 action (
986                                                 Parse<TKey> (c.OptionValues [0], c),
987                                                 Parse<TValue> (c.OptionValues [1], c));
988                         }
989                 }
990
991                 public OptionSet Add<T> (string prototype, Action<T> action)
992                 {
993                         return Add (prototype, null, action);
994                 }
995
996                 public OptionSet Add<T> (string prototype, string description, Action<T> action)
997                 {
998                         return Add (new ActionOption<T> (prototype, description, action));
999                 }
1000
1001                 public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
1002                 {
1003                         return Add (prototype, null, action);
1004                 }
1005
1006                 public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
1007                 {
1008                         return Add (new ActionOption<TKey, TValue> (prototype, description, action));
1009                 }
1010
1011                 public OptionSet Add (ArgumentSource source)
1012                 {
1013                         if (source == null)
1014                                 throw new ArgumentNullException ("source");
1015                         sources.Add (source);
1016                         return this;
1017                 }
1018
1019                 protected virtual OptionContext CreateOptionContext ()
1020                 {
1021                         return new OptionContext (this);
1022                 }
1023
1024                 public List<string> Parse (IEnumerable<string> arguments)
1025                 {
1026                         if (arguments == null)
1027                                 throw new ArgumentNullException ("arguments");
1028                         OptionContext c = CreateOptionContext ();
1029                         c.OptionIndex = -1;
1030                         bool process = true;
1031                         List<string> unprocessed = new List<string> ();
1032                         Option def = Contains ("<>") ? this ["<>"] : null;
1033                         ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
1034                         foreach (string argument in ae) {
1035                                 ++c.OptionIndex;
1036                                 if (argument == "--") {
1037                                         process = false;
1038                                         continue;
1039                                 }
1040                                 if (!process) {
1041                                         Unprocessed (unprocessed, def, c, argument);
1042                                         continue;
1043                                 }
1044                                 if (AddSource (ae, argument))
1045                                         continue;
1046                                 if (!Parse (argument, c))
1047                                         Unprocessed (unprocessed, def, c, argument);
1048                         }
1049                         if (c.Option != null)
1050                                 c.Option.Invoke (c);
1051                         return unprocessed;
1052                 }
1053
1054                 class ArgumentEnumerator : IEnumerable<string> {
1055                         List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
1056
1057                         public ArgumentEnumerator (IEnumerable<string> arguments)
1058                         {
1059                                 sources.Add (arguments.GetEnumerator ());
1060                         }
1061
1062                         public void Add (IEnumerable<string> arguments)
1063                         {
1064                                 sources.Add (arguments.GetEnumerator ());
1065                         }
1066
1067                         public IEnumerator<string> GetEnumerator ()
1068                         {
1069                                 do {
1070                                         IEnumerator<string> c = sources [sources.Count-1];
1071                                         if (c.MoveNext ())
1072                                                 yield return c.Current;
1073                                         else {
1074                                                 c.Dispose ();
1075                                                 sources.RemoveAt (sources.Count-1);
1076                                         }
1077                                 } while (sources.Count > 0);
1078                         }
1079
1080                         IEnumerator IEnumerable.GetEnumerator ()
1081                         {
1082                                 return GetEnumerator ();
1083                         }
1084                 }
1085
1086                 bool AddSource (ArgumentEnumerator ae, string argument)
1087                 {
1088                         foreach (ArgumentSource source in sources) {
1089                                 IEnumerable<string> replacement;
1090                                 if (!source.GetArguments (argument, out replacement))
1091                                         continue;
1092                                 ae.Add (replacement);
1093                                 return true;
1094                         }
1095                         return false;
1096                 }
1097
1098                 private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
1099                 {
1100                         if (def == null) {
1101                                 extra.Add (argument);
1102                                 return false;
1103                         }
1104                         c.OptionValues.Add (argument);
1105                         c.Option = def;
1106                         c.Option.Invoke (c);
1107                         return false;
1108                 }
1109
1110                 private readonly Regex ValueOption = new Regex (
1111                         @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
1112
1113                 protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
1114                 {
1115                         if (argument == null)
1116                                 throw new ArgumentNullException ("argument");
1117
1118                         flag = name = sep = value = null;
1119                         Match m = ValueOption.Match (argument);
1120                         if (!m.Success) {
1121                                 return false;
1122                         }
1123                         flag  = m.Groups ["flag"].Value;
1124                         name  = m.Groups ["name"].Value;
1125                         if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
1126                                 sep   = m.Groups ["sep"].Value;
1127                                 value = m.Groups ["value"].Value;
1128                         }
1129                         return true;
1130                 }
1131
1132                 protected virtual bool Parse (string argument, OptionContext c)
1133                 {
1134                         if (c.Option != null) {
1135                                 ParseValue (argument, c);
1136                                 return true;
1137                         }
1138
1139                         string f, n, s, v;
1140                         if (!GetOptionParts (argument, out f, out n, out s, out v))
1141                                 return false;
1142
1143                         Option p;
1144                         if (Contains (n)) {
1145                                 p = this [n];
1146                                 c.OptionName = f + n;
1147                                 c.Option     = p;
1148                                 switch (p.OptionValueType) {
1149                                         case OptionValueType.None:
1150                                                 c.OptionValues.Add (n);
1151                                                 c.Option.Invoke (c);
1152                                                 break;
1153                                         case OptionValueType.Optional:
1154                                         case OptionValueType.Required: 
1155                                                 ParseValue (v, c);
1156                                                 break;
1157                                 }
1158                                 return true;
1159                         }
1160                         // no match; is it a bool option?
1161                         if (ParseBool (argument, n, c))
1162                                 return true;
1163                         // is it a bundled option?
1164                         if (ParseBundledValue (f, string.Concat (n + s + v), c))
1165                                 return true;
1166
1167                         return false;
1168                 }
1169
1170                 private void ParseValue (string option, OptionContext c)
1171                 {
1172                         if (option != null)
1173                                 foreach (string o in c.Option.ValueSeparators != null 
1174                                                 ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
1175                                                 : new string[]{option}) {
1176                                         c.OptionValues.Add (o);
1177                                 }
1178                         if (c.OptionValues.Count == c.Option.MaxValueCount || 
1179                                         c.Option.OptionValueType == OptionValueType.Optional)
1180                                 c.Option.Invoke (c);
1181                         else if (c.OptionValues.Count > c.Option.MaxValueCount) {
1182                                 throw new OptionException (localizer (string.Format (
1183                                                                 "Error: Found {0} option values when expecting {1}.", 
1184                                                                 c.OptionValues.Count, c.Option.MaxValueCount)),
1185                                                 c.OptionName);
1186                         }
1187                 }
1188
1189                 private bool ParseBool (string option, string n, OptionContext c)
1190                 {
1191                         Option p;
1192                         string rn;
1193                         if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
1194                                         Contains ((rn = n.Substring (0, n.Length-1)))) {
1195                                 p = this [rn];
1196                                 string v = n [n.Length-1] == '+' ? option : null;
1197                                 c.OptionName  = option;
1198                                 c.Option      = p;
1199                                 c.OptionValues.Add (v);
1200                                 p.Invoke (c);
1201                                 return true;
1202                         }
1203                         return false;
1204                 }
1205
1206                 private bool ParseBundledValue (string f, string n, OptionContext c)
1207                 {
1208                         if (f != "-")
1209                                 return false;
1210                         for (int i = 0; i < n.Length; ++i) {
1211                                 Option p;
1212                                 string opt = f + n [i].ToString ();
1213                                 string rn = n [i].ToString ();
1214                                 if (!Contains (rn)) {
1215                                         if (i == 0)
1216                                                 return false;
1217                                         throw new OptionException (string.Format (localizer (
1218                                                                         "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null);
1219                                 }
1220                                 p = this [rn];
1221                                 switch (p.OptionValueType) {
1222                                         case OptionValueType.None:
1223                                                 Invoke (c, opt, n, p);
1224                                                 break;
1225                                         case OptionValueType.Optional:
1226                                         case OptionValueType.Required: {
1227                                                 string v     = n.Substring (i+1);
1228                                                 c.Option     = p;
1229                                                 c.OptionName = opt;
1230                                                 ParseValue (v.Length != 0 ? v : null, c);
1231                                                 return true;
1232                                         }
1233                                         default:
1234                                                 throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
1235                                 }
1236                         }
1237                         return true;
1238                 }
1239
1240                 private static void Invoke (OptionContext c, string name, string value, Option option)
1241                 {
1242                         c.OptionName  = name;
1243                         c.Option      = option;
1244                         c.OptionValues.Add (value);
1245                         option.Invoke (c);
1246                 }
1247
1248                 private const int OptionWidth = 29;
1249                 private const int Description_FirstWidth  = 80 - OptionWidth;
1250                 private const int Description_RemWidth    = 80 - OptionWidth - 2;
1251
1252                 static  readonly    string      CommandHelpIndentStart       = new string (' ', OptionWidth);
1253                 static  readonly    string      CommandHelpIndentRemaining   = new string (' ', OptionWidth + 2);
1254
1255                 public void WriteOptionDescriptions (TextWriter o)
1256                 {
1257                         foreach (Option p in this) {
1258                                 int written = 0;
1259
1260                                 if (p.Hidden)
1261                                         continue;
1262
1263                                 Category c = p as Category;
1264                                 if (c != null) {
1265                                         WriteDescription (o, p.Description, "", 80, 80);
1266                                         continue;
1267                                 }
1268                                 CommandOption co = p as CommandOption;
1269                                 if (co != null) {
1270                                         WriteCommandDescription (o, co.Command);
1271                                         continue;
1272                                 }
1273
1274                                 if (!WriteOptionPrototype (o, p, ref written))
1275                                         continue;
1276
1277                                 if (written < OptionWidth)
1278                                         o.Write (new string (' ', OptionWidth - written));
1279                                 else {
1280                                         o.WriteLine ();
1281                                         o.Write (new string (' ', OptionWidth));
1282                                 }
1283
1284                                 WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
1285                                                 Description_FirstWidth, Description_RemWidth);
1286                         }
1287
1288                         foreach (ArgumentSource s in sources) {
1289                                 string[] names = s.GetNames ();
1290                                 if (names == null || names.Length == 0)
1291                                         continue;
1292
1293                                 int written = 0;
1294
1295                                 Write (o, ref written, "  ");
1296                                 Write (o, ref written, names [0]);
1297                                 for (int i = 1; i < names.Length; ++i) {
1298                                         Write (o, ref written, ", ");
1299                                         Write (o, ref written, names [i]);
1300                                 }
1301
1302                                 if (written < OptionWidth)
1303                                         o.Write (new string (' ', OptionWidth - written));
1304                                 else {
1305                                         o.WriteLine ();
1306                                         o.Write (new string (' ', OptionWidth));
1307                                 }
1308
1309                                 WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
1310                                                 Description_FirstWidth, Description_RemWidth);
1311                         }
1312                 }
1313
1314                 internal void WriteCommandDescription (TextWriter o, Command c)
1315                 {
1316                         var name = new string (' ', 8) + c.Name;
1317                         if (name.Length < OptionWidth - 1) {
1318                                 WriteDescription (o, name + new string (' ', OptionWidth - name.Length) + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth);
1319                         } else {
1320                                 WriteDescription (o, name, "", 80, 80);
1321                                 WriteDescription (o, CommandHelpIndentStart + c.Help, CommandHelpIndentRemaining, 80, Description_RemWidth);
1322                         }
1323                 }
1324
1325                 void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
1326                 {
1327                         bool indent = false;
1328                         foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
1329                                 if (indent)
1330                                         o.Write (prefix);
1331                                 o.WriteLine (line);
1332                                 indent = true;
1333                         }
1334                 }
1335
1336                 bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
1337                 {
1338                         string[] names = p.Names;
1339
1340                         int i = GetNextOptionIndex (names, 0);
1341                         if (i == names.Length)
1342                                 return false;
1343
1344                         if (names [i].Length == 1) {
1345                                 Write (o, ref written, "  -");
1346                                 Write (o, ref written, names [0]);
1347                         }
1348                         else {
1349                                 Write (o, ref written, "      --");
1350                                 Write (o, ref written, names [0]);
1351                         }
1352
1353                         for ( i = GetNextOptionIndex (names, i+1); 
1354                                         i < names.Length; i = GetNextOptionIndex (names, i+1)) {
1355                                 Write (o, ref written, ", ");
1356                                 Write (o, ref written, names [i].Length == 1 ? "-" : "--");
1357                                 Write (o, ref written, names [i]);
1358                         }
1359
1360                         if (p.OptionValueType == OptionValueType.Optional ||
1361                                         p.OptionValueType == OptionValueType.Required) {
1362                                 if (p.OptionValueType == OptionValueType.Optional) {
1363                                         Write (o, ref written, localizer ("["));
1364                                 }
1365                                 Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
1366                                 string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 
1367                                         ? p.ValueSeparators [0]
1368                                         : " ";
1369                                 for (int c = 1; c < p.MaxValueCount; ++c) {
1370                                         Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
1371                                 }
1372                                 if (p.OptionValueType == OptionValueType.Optional) {
1373                                         Write (o, ref written, localizer ("]"));
1374                                 }
1375                         }
1376                         return true;
1377                 }
1378
1379                 static int GetNextOptionIndex (string[] names, int i)
1380                 {
1381                         while (i < names.Length && names [i] == "<>") {
1382                                 ++i;
1383                         }
1384                         return i;
1385                 }
1386
1387                 static void Write (TextWriter o, ref int n, string s)
1388                 {
1389                         n += s.Length;
1390                         o.Write (s);
1391                 }
1392
1393                 private static string GetArgumentName (int index, int maxIndex, string description)
1394                 {
1395                         if (description == null)
1396                                 return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1397                         string[] nameStart;
1398                         if (maxIndex == 1)
1399                                 nameStart = new string[]{"{0:", "{"};
1400                         else
1401                                 nameStart = new string[]{"{" + index + ":"};
1402                         for (int i = 0; i < nameStart.Length; ++i) {
1403                                 int start, j = 0;
1404                                 do {
1405                                         start = description.IndexOf (nameStart [i], j);
1406                                 } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
1407                                 if (start == -1)
1408                                         continue;
1409                                 int end = description.IndexOf ("}", start);
1410                                 if (end == -1)
1411                                         continue;
1412                                 return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
1413                         }
1414                         return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
1415                 }
1416
1417                 private static string GetDescription (string description)
1418                 {
1419                         if (description == null)
1420                                 return string.Empty;
1421                         StringBuilder sb = new StringBuilder (description.Length);
1422                         int start = -1;
1423                         for (int i = 0; i < description.Length; ++i) {
1424                                 switch (description [i]) {
1425                                         case '{':
1426                                                 if (i == start) {
1427                                                         sb.Append ('{');
1428                                                         start = -1;
1429                                                 }
1430                                                 else if (start < 0)
1431                                                         start = i + 1;
1432                                                 break;
1433                                         case '}':
1434                                                 if (start < 0) {
1435                                                         if ((i+1) == description.Length || description [i+1] != '}')
1436                                                                 throw new InvalidOperationException ("Invalid option description: " + description);
1437                                                         ++i;
1438                                                         sb.Append ("}");
1439                                                 }
1440                                                 else {
1441                                                         sb.Append (description.Substring (start, i - start));
1442                                                         start = -1;
1443                                                 }
1444                                                 break;
1445                                         case ':':
1446                                                 if (start < 0)
1447                                                         goto default;
1448                                                 start = i + 1;
1449                                                 break;
1450                                         default:
1451                                                 if (start < 0)
1452                                                         sb.Append (description [i]);
1453                                                 break;
1454                                 }
1455                         }
1456                         return sb.ToString ();
1457                 }
1458
1459                 private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
1460                 {
1461                         return StringCoda.WrappedLines (description, firstWidth, remWidth);
1462                 }
1463         }
1464
1465         public class Command
1466         {
1467                 public      string                              Name            {get;}
1468                 public      string                              Help            {get;}
1469
1470                 public      OptionSet                           Options         {get; set;}
1471                 public      Action<IEnumerable<string>>         Run             {get; set;}
1472
1473                 public      CommandSet                          CommandSet      {get; internal set;}
1474
1475                 public Command (string name, string help = null)
1476                 {
1477                         if (string.IsNullOrEmpty (name))
1478                                 throw new ArgumentNullException (nameof (name));
1479
1480                         Name    = name;
1481                         Help    = help;
1482                 }
1483
1484                 public virtual int Invoke (IEnumerable<string> arguments)
1485                 {
1486                         var rest    = Options?.Parse (arguments) ?? arguments;
1487                         Run?.Invoke (rest);
1488                         return 0;
1489                 }
1490         }
1491
1492         class CommandOption : Option
1493         {
1494                 public      Command             Command         {get;}
1495
1496                 // Prototype starts with '=' because this is an invalid prototype
1497                 // (see Option.ParsePrototype(), and thus it'll prevent Category
1498                 // instances from being accidentally used as normal options.
1499                 public CommandOption (Command command, bool hidden = false)
1500                         : base ("=:Command:= " + command?.Name, command?.Name, maxValueCount: 0, hidden: hidden)
1501                 {
1502                         if (command == null)
1503                                 throw new ArgumentNullException (nameof (command));
1504                         Command = command;
1505                 }
1506
1507                 protected override void OnParseComplete (OptionContext c)
1508                 {
1509                         throw new NotSupportedException ("CommandOption.OnParseComplete should not be invoked.");
1510                 }
1511         }
1512
1513         class HelpOption : Option
1514         {
1515                 Option      option;
1516                 CommandSet  commands;
1517
1518                 public HelpOption (CommandSet commands, Option d)
1519                         : base (d.Prototype, d.Description, d.MaxValueCount, d.Hidden)
1520                 {
1521                         this.commands   = commands;
1522                         this.option     = d;
1523                 }
1524
1525                 protected override void OnParseComplete (OptionContext c)
1526                 {
1527                         commands.showHelp  = true;
1528
1529                         option?.InvokeOnParseComplete (c);
1530                 }
1531         }
1532
1533         class CommandOptionSet : OptionSet
1534         {
1535                 CommandSet  commands;
1536
1537                 public CommandOptionSet (CommandSet commands, MessageLocalizerConverter localizer)
1538                         : base (localizer)
1539                 {
1540                         this.commands = commands;
1541                 }
1542
1543                 protected override void SetItem (int index, Option item)
1544                 {
1545                         if (ShouldWrapOption (item)) {
1546                                 base.SetItem (index, new HelpOption (commands, item));
1547                                 return;
1548                         }
1549                         base.SetItem (index, item);
1550                 }
1551
1552                 bool ShouldWrapOption (Option item)
1553                 {
1554                         if (item == null)
1555                                 return false;
1556                         var help = item as HelpOption;
1557                         if (help != null)
1558                                 return false;
1559                         foreach (var n in item.Names) {
1560                                 if (n == "help")
1561                                         return true;
1562                         }
1563                         return false;
1564                 }
1565
1566                 protected override void InsertItem (int index, Option item)
1567                 {
1568                         if (ShouldWrapOption (item)) {
1569                                 base.InsertItem (index, new HelpOption (commands, item));
1570                                 return;
1571                         }
1572                         base.InsertItem (index, item);
1573                 }
1574         }
1575
1576         public class CommandSet : KeyedCollection<string, Command>
1577         {
1578                 readonly    OptionSet       options;
1579                 readonly    TextWriter      outWriter;
1580                 readonly    TextWriter      errorWriter;
1581                 readonly    string          suite;
1582
1583                 HelpCommand help;
1584
1585                 internal    bool            showHelp;
1586
1587                 internal    OptionSet       Options     => options;
1588
1589                 public CommandSet (string suite, MessageLocalizerConverter localizer = null, TextWriter output = null, TextWriter error = null)
1590                 {
1591                         if (suite == null)
1592                                 throw new ArgumentNullException (nameof (suite));
1593                         this.suite  = suite;
1594                         options     = new CommandOptionSet (this, localizer);
1595                         outWriter   = output    ?? Console.Out;
1596                         errorWriter = error     ?? Console.Error;
1597                 }
1598
1599                 public  string                          Suite               => suite;
1600                 public  TextWriter                      Out                 => outWriter;
1601                 public  TextWriter                      Error               => errorWriter;
1602                 public  MessageLocalizerConverter       MessageLocalizer    => options.MessageLocalizer;
1603
1604                 protected override string GetKeyForItem (Command item)
1605                 {
1606                         return item?.Name;
1607                 }
1608
1609                 public new CommandSet Add (Command value)
1610                 {
1611                         if (value == null)
1612                                 throw new ArgumentNullException (nameof (value));
1613                         AddCommand (value);
1614                         options.Add (new CommandOption (value));
1615                         return this;
1616                 }
1617
1618                 void AddCommand (Command value)
1619                 {
1620                         if (value.CommandSet != null && value.CommandSet != this) {
1621                                 throw new ArgumentException ("Command instances can only be added to a single CommandSet.", nameof (value));
1622                         }
1623                         value.CommandSet                = this;
1624                         if (value.Options != null) {
1625                                 value.Options.MessageLocalizer  = options.MessageLocalizer;
1626                         }
1627
1628                         base.Add (value);
1629
1630                         help    = help ?? value as HelpCommand;
1631                 }
1632
1633                 public CommandSet Add (string header)
1634                 {
1635                         options.Add (header);
1636                         return this;
1637                 }
1638
1639                 public CommandSet Add (Option option)
1640                 {
1641                         options.Add (option);
1642                         return this;
1643                 }
1644
1645                 public CommandSet Add (string prototype, Action<string> action)
1646                 {
1647                         options.Add (prototype, action);
1648                         return this;
1649                 }
1650
1651                 public CommandSet Add (string prototype, string description, Action<string> action)
1652                 {
1653                         options.Add (prototype, description, action);
1654                         return this;
1655                 }
1656
1657                 public CommandSet Add (string prototype, string description, Action<string> action, bool hidden)
1658                 {
1659                         options.Add (prototype, description, action, hidden);
1660                         return this;
1661                 }
1662
1663                 public CommandSet Add (string prototype, OptionAction<string, string> action)
1664                 {
1665                         options.Add (prototype, action);
1666                         return this;
1667                 }
1668
1669                 public CommandSet Add (string prototype, string description, OptionAction<string, string> action)
1670                 {
1671                         options.Add (prototype, description, action);
1672                         return this;
1673                 }
1674
1675                 public CommandSet Add (string prototype, string description, OptionAction<string, string> action, bool hidden)
1676                 {
1677                         options.Add (prototype, description, action, hidden);
1678                         return this;
1679                 }
1680
1681                 public CommandSet Add<T> (string prototype, Action<T> action)
1682                 {
1683                         options.Add (prototype, null, action);
1684                         return this;
1685                 }
1686
1687                 public CommandSet Add<T> (string prototype, string description, Action<T> action)
1688                 {
1689                         options.Add (prototype, description, action);
1690                         return this;
1691                 }
1692
1693                 public CommandSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
1694                 {
1695                         options.Add (prototype, action);
1696                         return this;
1697                 }
1698
1699                 public CommandSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
1700                 {
1701                         options.Add (prototype, description, action);
1702                         return this;
1703                 }
1704
1705                 public CommandSet Add (ArgumentSource source)
1706                 {
1707                         options.Add (source);
1708                         return this;
1709                 }
1710
1711                 public int Run (IEnumerable<string> arguments)
1712                 {
1713                         if (arguments == null)
1714                                 throw new ArgumentNullException (nameof (arguments));
1715
1716                         this.showHelp   = false;
1717                         if (help == null) {
1718                                 help    = new HelpCommand ();
1719                                 AddCommand (help);
1720                         }
1721                         Action<string>  setHelp     = v => showHelp = v != null;
1722                         if (!options.Contains ("help")) {
1723                                 options.Add ("help", "", setHelp, hidden: true);
1724                         }
1725                         if (!options.Contains ("?")) {
1726                                 options.Add ("?", "", setHelp, hidden: true);
1727                         }
1728                         var extra   = options.Parse (arguments);
1729                         if (extra.Count == 0) {
1730                                 if (showHelp) {
1731                                         return help.Invoke (extra);
1732                                 }
1733                                 Out.WriteLine (options.MessageLocalizer ($"Use `{Suite} help` for usage."));
1734                                 return 1;
1735                         }
1736                         var command = Contains (extra [0]) ? this [extra [0]] : null;
1737                         if (command == null) {
1738                                 help.WriteUnknownCommand (extra [0]);
1739                                 return 1;
1740                         }
1741                         extra.RemoveAt (0);
1742                         if (showHelp) {
1743                                 if (command.Options?.Contains ("help") ?? true) {
1744                                         extra.Add ("--help");
1745                                         return command.Invoke (extra);
1746                                 }
1747                                 command.Options.WriteOptionDescriptions (Out);
1748                                 return 0;
1749                         }
1750                         return command.Invoke (extra);
1751                 }
1752         }
1753
1754         public class HelpCommand : Command
1755         {
1756                 public HelpCommand ()
1757                         : base ("help", help: "Show this message and exit")
1758                 {
1759                 }
1760
1761                 public override int Invoke (IEnumerable<string> arguments)
1762                 {
1763                         var extra   = new List<string> (arguments ?? new string [0]);
1764                         var _       = CommandSet.Options.MessageLocalizer;
1765                         if (extra.Count == 0) {
1766                                 CommandSet.Options.WriteOptionDescriptions (CommandSet.Out);
1767                                 return 0;
1768                         }
1769                         var command = CommandSet.Contains (extra [0])
1770                                 ? CommandSet [extra [0]]
1771                                 : null;
1772                         if (command == this || extra [0] == "--help") {
1773                                 CommandSet.Out.WriteLine (_ ($"Usage: {CommandSet.Suite} COMMAND [OPTIONS]"));
1774                                 CommandSet.Out.WriteLine (_ ($"Use `{CommandSet.Suite} help COMMAND` for help on a specific command."));
1775                                 CommandSet.Out.WriteLine ();
1776                                 CommandSet.Out.WriteLine (_ ($"Available commands:"));
1777                                 CommandSet.Out.WriteLine ();
1778                                 foreach (var c in CommandSet) {
1779                                         CommandSet.Options.WriteCommandDescription (CommandSet.Out, c);
1780                                 }
1781                                 return 0;
1782                         }
1783                         if (command == null) {
1784                                 WriteUnknownCommand (extra [0]);
1785                                 return 1;
1786                         }
1787                         if (command.Options != null) {
1788                                 command.Options.WriteOptionDescriptions (CommandSet.Out);
1789                                 return 0;
1790                         }
1791                         return command.Invoke (new [] { "--help" });
1792                 }
1793
1794                 internal void WriteUnknownCommand (string unknownCommand)
1795                 {
1796                         CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Unknown command: {unknownCommand}"));
1797                         CommandSet.Error.WriteLine (CommandSet.Options.MessageLocalizer ($"{CommandSet.Suite}: Use `{CommandSet.Suite} help` for usage."));
1798                 }
1799         }
1800 }
1801