PageRenderTime 70ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/Echo/Mono.Options/Options.cs

https://bitbucket.org/emertechie/csvlogtailer
C# | 1344 lines | 1150 code | 65 blank | 129 comment | 93 complexity | 8d062262b4fe62613c7dfe33394e6f5b MD5 | raw file
  1. //
  2. // Options.cs
  3. //
  4. // Authors:
  5. // Jonathan Pryor <jpryor@novell.com>
  6. // Federico Di Gregorio <fog@initd.org>
  7. //
  8. // Copyright (C) 2008 Novell (http://www.novell.com)
  9. // Copyright (C) 2009 Federico Di Gregorio.
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. // Compile With:
  31. // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
  32. // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
  33. //
  34. // The LINQ version just changes the implementation of
  35. // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
  36. //
  37. // A Getopt::Long-inspired option parsing library for C#.
  38. //
  39. // NDesk.Options.OptionSet is built upon a key/value table, where the
  40. // key is a option format string and the value is a delegate that is
  41. // invoked when the format string is matched.
  42. //
  43. // Option format strings:
  44. // Regex-like BNF Grammar:
  45. // name: .+
  46. // type: [=:]
  47. // sep: ( [^{}]+ | '{' .+ '}' )?
  48. // aliases: ( name type sep ) ( '|' name type sep )*
  49. //
  50. // Each '|'-delimited name is an alias for the associated action. If the
  51. // format string ends in a '=', it has a required value. If the format
  52. // string ends in a ':', it has an optional value. If neither '=' or ':'
  53. // is present, no value is supported. `=' or `:' need only be defined on one
  54. // alias, but if they are provided on more than one they must be consistent.
  55. //
  56. // Each alias portion may also end with a "key/value separator", which is used
  57. // to split option values if the option accepts > 1 value. If not specified,
  58. // it defaults to '=' and ':'. If specified, it can be any character except
  59. // '{' and '}' OR the *string* between '{' and '}'. If no separator should be
  60. // used (i.e. the separate values should be distinct arguments), then "{}"
  61. // should be used as the separator.
  62. //
  63. // Options are extracted either from the current option by looking for
  64. // the option name followed by an '=' or ':', or is taken from the
  65. // following option IFF:
  66. // - The current option does not contain a '=' or a ':'
  67. // - The current option requires a value (i.e. not a Option type of ':')
  68. //
  69. // The `name' used in the option format string does NOT include any leading
  70. // option indicator, such as '-', '--', or '/'. All three of these are
  71. // permitted/required on any named option.
  72. //
  73. // Option bundling is permitted so long as:
  74. // - '-' is used to start the option group
  75. // - all of the bundled options are a single character
  76. // - at most one of the bundled options accepts a value, and the value
  77. // provided starts from the next character to the end of the string.
  78. //
  79. // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
  80. // as '-Dname=value'.
  81. //
  82. // Option processing is disabled by specifying "--". All options after "--"
  83. // are returned by OptionSet.Parse() unchanged and unprocessed.
  84. //
  85. // Unprocessed options are returned from OptionSet.Parse().
  86. //
  87. // Examples:
  88. // int verbose = 0;
  89. // OptionSet p = new OptionSet ()
  90. // .Add ("v", v => ++verbose)
  91. // .Add ("name=|value=", v => Console.WriteLine (v));
  92. // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
  93. //
  94. // The above would parse the argument string array, and would invoke the
  95. // lambda expression three times, setting `verbose' to 3 when complete.
  96. // It would also print out "A" and "B" to standard output.
  97. // The returned array would contain the string "extra".
  98. //
  99. // C# 3.0 collection initializers are supported and encouraged:
  100. // var p = new OptionSet () {
  101. // { "h|?|help", v => ShowHelp () },
  102. // };
  103. //
  104. // System.ComponentModel.TypeConverter is also supported, allowing the use of
  105. // custom data types in the callback type; TypeConverter.ConvertFromString()
  106. // is used to convert the value option to an instance of the specified
  107. // type:
  108. //
  109. // var p = new OptionSet () {
  110. // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
  111. // };
  112. //
  113. // Random other tidbits:
  114. // - Boolean options (those w/o '=' or ':' in the option format string)
  115. // are explicitly enabled if they are followed with '+', and explicitly
  116. // disabled if they are followed with '-':
  117. // string a = null;
  118. // var p = new OptionSet () {
  119. // { "a", s => a = s },
  120. // };
  121. // p.Parse (new string[]{"-a"}); // sets v != null
  122. // p.Parse (new string[]{"-a+"}); // sets v != null
  123. // p.Parse (new string[]{"-a-"}); // sets v == null
  124. //
  125. using System;
  126. using System.Collections;
  127. using System.Collections.Generic;
  128. using System.Collections.ObjectModel;
  129. using System.ComponentModel;
  130. using System.Globalization;
  131. using System.IO;
  132. using System.Runtime.Serialization;
  133. using System.Security.Permissions;
  134. using System.Text;
  135. using System.Text.RegularExpressions;
  136. #if LINQ
  137. using System.Linq;
  138. #endif
  139. #if TEST
  140. using NDesk.Options;
  141. #endif
  142. #if NDESK_OPTIONS
  143. namespace NDesk.Options
  144. #else
  145. namespace Mono.Options
  146. #endif
  147. {
  148. static class StringCoda {
  149. public static IEnumerable<string> WrappedLines (string self, params int[] widths)
  150. {
  151. IEnumerable<int> w = widths;
  152. return WrappedLines (self, w);
  153. }
  154. public static IEnumerable<string> WrappedLines (string self, IEnumerable<int> widths)
  155. {
  156. if (widths == null)
  157. throw new ArgumentNullException ("widths");
  158. return CreateWrappedLinesIterator (self, widths);
  159. }
  160. private static IEnumerable<string> CreateWrappedLinesIterator (string self, IEnumerable<int> widths)
  161. {
  162. if (string.IsNullOrEmpty (self)) {
  163. yield return string.Empty;
  164. yield break;
  165. }
  166. using (IEnumerator<int> ewidths = widths.GetEnumerator ()) {
  167. bool? hw = null;
  168. int width = GetNextWidth (ewidths, int.MaxValue, ref hw);
  169. int start = 0, end;
  170. do {
  171. end = GetLineEnd (start, width, self);
  172. char c = self [end-1];
  173. if (char.IsWhiteSpace (c))
  174. --end;
  175. bool needContinuation = end != self.Length && !IsEolChar (c);
  176. string continuation = "";
  177. if (needContinuation) {
  178. --end;
  179. continuation = "-";
  180. }
  181. string line = self.Substring (start, end - start) + continuation;
  182. yield return line;
  183. start = end;
  184. if (char.IsWhiteSpace (c))
  185. ++start;
  186. width = GetNextWidth (ewidths, width, ref hw);
  187. } while (start < self.Length);
  188. }
  189. }
  190. private static int GetNextWidth (IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
  191. {
  192. if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) {
  193. curWidth = (eValid = ewidths.MoveNext ()).Value ? ewidths.Current : curWidth;
  194. // '.' is any character, - is for a continuation
  195. const string minWidth = ".-";
  196. if (curWidth < minWidth.Length)
  197. throw new ArgumentOutOfRangeException ("widths",
  198. string.Format ("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
  199. return curWidth;
  200. }
  201. // no more elements, use the last element.
  202. return curWidth;
  203. }
  204. private static bool IsEolChar (char c)
  205. {
  206. return !char.IsLetterOrDigit (c);
  207. }
  208. private static int GetLineEnd (int start, int length, string description)
  209. {
  210. int end = System.Math.Min (start + length, description.Length);
  211. int sep = -1;
  212. for (int i = start; i < end; ++i) {
  213. if (description [i] == '\n')
  214. return i+1;
  215. if (IsEolChar (description [i]))
  216. sep = i+1;
  217. }
  218. if (sep == -1 || end == description.Length)
  219. return end;
  220. return sep;
  221. }
  222. }
  223. internal class OptionValueCollection : IList, IList<string> {
  224. List<string> values = new List<string> ();
  225. OptionContext c;
  226. internal OptionValueCollection (OptionContext c)
  227. {
  228. this.c = c;
  229. }
  230. #region ICollection
  231. void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
  232. bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
  233. object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
  234. #endregion
  235. #region ICollection<T>
  236. public void Add (string item) {values.Add (item);}
  237. public void Clear () {values.Clear ();}
  238. public bool Contains (string item) {return values.Contains (item);}
  239. public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
  240. public bool Remove (string item) {return values.Remove (item);}
  241. public int Count {get {return values.Count;}}
  242. public bool IsReadOnly {get {return false;}}
  243. #endregion
  244. #region IEnumerable
  245. IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
  246. #endregion
  247. #region IEnumerable<T>
  248. public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();}
  249. #endregion
  250. #region IList
  251. int IList.Add (object value) {return (values as IList).Add (value);}
  252. bool IList.Contains (object value) {return (values as IList).Contains (value);}
  253. int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
  254. void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
  255. void IList.Remove (object value) {(values as IList).Remove (value);}
  256. void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
  257. bool IList.IsFixedSize {get {return false;}}
  258. object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
  259. #endregion
  260. #region IList<T>
  261. public int IndexOf (string item) {return values.IndexOf (item);}
  262. public void Insert (int index, string item) {values.Insert (index, item);}
  263. public void RemoveAt (int index) {values.RemoveAt (index);}
  264. private void AssertValid (int index)
  265. {
  266. if (c.Option == null)
  267. throw new InvalidOperationException ("OptionContext.Option is null.");
  268. if (index >= c.Option.MaxValueCount)
  269. throw new ArgumentOutOfRangeException ("index");
  270. if (c.Option.OptionValueType == OptionValueType.Required &&
  271. index >= values.Count)
  272. throw new OptionException (string.Format (
  273. c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
  274. c.OptionName);
  275. }
  276. public string this [int index] {
  277. get {
  278. AssertValid (index);
  279. return index >= values.Count ? null : values [index];
  280. }
  281. set {
  282. values [index] = value;
  283. }
  284. }
  285. #endregion
  286. public List<string> ToList ()
  287. {
  288. return new List<string> (values);
  289. }
  290. public string[] ToArray ()
  291. {
  292. return values.ToArray ();
  293. }
  294. public override string ToString ()
  295. {
  296. return string.Join (", ", values.ToArray ());
  297. }
  298. }
  299. internal class OptionContext
  300. {
  301. private Option option;
  302. private string name;
  303. private int index;
  304. private OptionSet set;
  305. private OptionValueCollection c;
  306. public OptionContext (OptionSet set)
  307. {
  308. this.set = set;
  309. this.c = new OptionValueCollection (this);
  310. }
  311. public Option Option {
  312. get {return option;}
  313. set {option = value;}
  314. }
  315. public string OptionName {
  316. get {return name;}
  317. set {name = value;}
  318. }
  319. public int OptionIndex {
  320. get {return index;}
  321. set {index = value;}
  322. }
  323. public OptionSet OptionSet {
  324. get {return set;}
  325. }
  326. public OptionValueCollection OptionValues {
  327. get {return c;}
  328. }
  329. }
  330. internal enum OptionValueType
  331. {
  332. None,
  333. Optional,
  334. Required,
  335. }
  336. internal abstract class Option
  337. {
  338. string prototype, description;
  339. string[] names;
  340. OptionValueType type;
  341. int count;
  342. string[] separators;
  343. protected Option (string prototype, string description)
  344. : this (prototype, description, 1)
  345. {
  346. }
  347. protected Option (string prototype, string description, int maxValueCount)
  348. {
  349. if (prototype == null)
  350. throw new ArgumentNullException ("prototype");
  351. if (prototype.Length == 0)
  352. throw new ArgumentException ("Cannot be the empty string.", "prototype");
  353. if (maxValueCount < 0)
  354. throw new ArgumentOutOfRangeException ("maxValueCount");
  355. this.prototype = prototype;
  356. this.description = description;
  357. this.count = maxValueCount;
  358. this.names = (this is OptionSet.Category)
  359. // append GetHashCode() so that "duplicate" categories have distinct
  360. // names, e.g. adding multiple "" categories should be valid.
  361. ? new[]{prototype + this.GetHashCode ()}
  362. : prototype.Split ('|');
  363. if (this is OptionSet.Category)
  364. return;
  365. this.type = ParsePrototype ();
  366. if (this.count == 0 && type != OptionValueType.None)
  367. throw new ArgumentException (
  368. "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
  369. "OptionValueType.Optional.",
  370. "maxValueCount");
  371. if (this.type == OptionValueType.None && maxValueCount > 1)
  372. throw new ArgumentException (
  373. string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
  374. "maxValueCount");
  375. if (Array.IndexOf (names, "<>") >= 0 &&
  376. ((names.Length == 1 && this.type != OptionValueType.None) ||
  377. (names.Length > 1 && this.MaxValueCount > 1)))
  378. throw new ArgumentException (
  379. "The default option handler '<>' cannot require values.",
  380. "prototype");
  381. }
  382. public string Prototype {get {return prototype;}}
  383. public string Description {get {return description;}}
  384. public OptionValueType OptionValueType {get {return type;}}
  385. public int MaxValueCount {get {return count;}}
  386. public string[] GetNames ()
  387. {
  388. return (string[]) names.Clone ();
  389. }
  390. public string[] GetValueSeparators ()
  391. {
  392. if (separators == null)
  393. return new string [0];
  394. return (string[]) separators.Clone ();
  395. }
  396. protected static T Parse<T> (string value, OptionContext c)
  397. {
  398. Type tt = typeof (T);
  399. bool nullable = tt.IsValueType && tt.IsGenericType &&
  400. !tt.IsGenericTypeDefinition &&
  401. tt.GetGenericTypeDefinition () == typeof (Nullable<>);
  402. Type targetType = nullable ? tt.GetGenericArguments () [0] : typeof (T);
  403. TypeConverter conv = TypeDescriptor.GetConverter (targetType);
  404. T t = default (T);
  405. try {
  406. if (value != null)
  407. t = (T) conv.ConvertFromString (value);
  408. }
  409. catch (Exception e) {
  410. throw new OptionException (
  411. string.Format (
  412. c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
  413. value, targetType.Name, c.OptionName),
  414. c.OptionName, e);
  415. }
  416. return t;
  417. }
  418. internal string[] Names {get {return names;}}
  419. internal string[] ValueSeparators {get {return separators;}}
  420. static readonly char[] NameTerminator = new char[]{'=', ':'};
  421. private OptionValueType ParsePrototype ()
  422. {
  423. char type = '\0';
  424. List<string> seps = new List<string> ();
  425. for (int i = 0; i < names.Length; ++i) {
  426. string name = names [i];
  427. if (name.Length == 0)
  428. throw new ArgumentException ("Empty option names are not supported.", "prototype");
  429. int end = name.IndexOfAny (NameTerminator);
  430. if (end == -1)
  431. continue;
  432. names [i] = name.Substring (0, end);
  433. if (type == '\0' || type == name [end])
  434. type = name [end];
  435. else
  436. throw new ArgumentException (
  437. string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
  438. "prototype");
  439. AddSeparators (name, end, seps);
  440. }
  441. if (type == '\0')
  442. return OptionValueType.None;
  443. if (count <= 1 && seps.Count != 0)
  444. throw new ArgumentException (
  445. string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
  446. "prototype");
  447. if (count > 1) {
  448. if (seps.Count == 0)
  449. this.separators = new string[]{":", "="};
  450. else if (seps.Count == 1 && seps [0].Length == 0)
  451. this.separators = null;
  452. else
  453. this.separators = seps.ToArray ();
  454. }
  455. return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
  456. }
  457. private static void AddSeparators (string name, int end, ICollection<string> seps)
  458. {
  459. int start = -1;
  460. for (int i = end+1; i < name.Length; ++i) {
  461. switch (name [i]) {
  462. case '{':
  463. if (start != -1)
  464. throw new ArgumentException (
  465. string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
  466. "prototype");
  467. start = i+1;
  468. break;
  469. case '}':
  470. if (start == -1)
  471. throw new ArgumentException (
  472. string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
  473. "prototype");
  474. seps.Add (name.Substring (start, i-start));
  475. start = -1;
  476. break;
  477. default:
  478. if (start == -1)
  479. seps.Add (name [i].ToString ());
  480. break;
  481. }
  482. }
  483. if (start != -1)
  484. throw new ArgumentException (
  485. string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
  486. "prototype");
  487. }
  488. public void Invoke (OptionContext c)
  489. {
  490. OnParseComplete (c);
  491. c.OptionName = null;
  492. c.Option = null;
  493. c.OptionValues.Clear ();
  494. }
  495. protected abstract void OnParseComplete (OptionContext c);
  496. public override string ToString ()
  497. {
  498. return Prototype;
  499. }
  500. }
  501. internal abstract class ArgumentSource {
  502. protected ArgumentSource ()
  503. {
  504. }
  505. public abstract string[] GetNames ();
  506. public abstract string Description { get; }
  507. public abstract bool GetArguments (string value, out IEnumerable<string> replacement);
  508. public static IEnumerable<string> GetArgumentsFromFile (string file)
  509. {
  510. return GetArguments (File.OpenText (file), true);
  511. }
  512. public static IEnumerable<string> GetArguments (TextReader reader)
  513. {
  514. return GetArguments (reader, false);
  515. }
  516. // Cribbed from mcs/driver.cs:LoadArgs(string)
  517. static IEnumerable<string> GetArguments (TextReader reader, bool close)
  518. {
  519. try {
  520. StringBuilder arg = new StringBuilder ();
  521. string line;
  522. while ((line = reader.ReadLine ()) != null) {
  523. int t = line.Length;
  524. for (int i = 0; i < t; i++) {
  525. char c = line [i];
  526. if (c == '"' || c == '\'') {
  527. char end = c;
  528. for (i++; i < t; i++){
  529. c = line [i];
  530. if (c == end)
  531. break;
  532. arg.Append (c);
  533. }
  534. } else if (c == ' ') {
  535. if (arg.Length > 0) {
  536. yield return arg.ToString ();
  537. arg.Length = 0;
  538. }
  539. } else
  540. arg.Append (c);
  541. }
  542. if (arg.Length > 0) {
  543. yield return arg.ToString ();
  544. arg.Length = 0;
  545. }
  546. }
  547. }
  548. finally {
  549. if (close)
  550. reader.Close ();
  551. }
  552. }
  553. }
  554. internal class ResponseFileSource : ArgumentSource
  555. {
  556. public override string[] GetNames ()
  557. {
  558. return new string[]{"@file"};
  559. }
  560. public override string Description {
  561. get {return "Read response file for more options.";}
  562. }
  563. public override bool GetArguments (string value, out IEnumerable<string> replacement)
  564. {
  565. if (string.IsNullOrEmpty (value) || !value.StartsWith ("@")) {
  566. replacement = null;
  567. return false;
  568. }
  569. replacement = ArgumentSource.GetArgumentsFromFile (value.Substring (1));
  570. return true;
  571. }
  572. }
  573. [Serializable]
  574. internal class OptionException : Exception
  575. {
  576. private string option;
  577. public OptionException ()
  578. {
  579. }
  580. public OptionException (string message, string optionName)
  581. : base (message)
  582. {
  583. this.option = optionName;
  584. }
  585. public OptionException (string message, string optionName, Exception innerException)
  586. : base (message, innerException)
  587. {
  588. this.option = optionName;
  589. }
  590. protected OptionException (SerializationInfo info, StreamingContext context)
  591. : base (info, context)
  592. {
  593. this.option = info.GetString ("OptionName");
  594. }
  595. public string OptionName {
  596. get {return this.option;}
  597. }
  598. [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
  599. public override void GetObjectData (SerializationInfo info, StreamingContext context)
  600. {
  601. base.GetObjectData (info, context);
  602. info.AddValue ("OptionName", option);
  603. }
  604. }
  605. internal delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
  606. internal class OptionSet : KeyedCollection<string, Option>
  607. {
  608. public OptionSet ()
  609. : this (delegate (string f) {return f;})
  610. {
  611. }
  612. public OptionSet (Converter<string, string> localizer)
  613. {
  614. this.localizer = localizer;
  615. this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
  616. }
  617. Converter<string, string> localizer;
  618. public Converter<string, string> MessageLocalizer {
  619. get {return localizer;}
  620. }
  621. List<ArgumentSource> sources = new List<ArgumentSource> ();
  622. ReadOnlyCollection<ArgumentSource> roSources;
  623. public ReadOnlyCollection<ArgumentSource> ArgumentSources {
  624. get {return roSources;}
  625. }
  626. protected override string GetKeyForItem (Option item)
  627. {
  628. if (item == null)
  629. throw new ArgumentNullException ("option");
  630. if (item.Names != null && item.Names.Length > 0)
  631. return item.Names [0];
  632. // This should never happen, as it's invalid for Option to be
  633. // constructed w/o any names.
  634. throw new InvalidOperationException ("Option has no names!");
  635. }
  636. [Obsolete ("Use KeyedCollection.this[string]")]
  637. protected Option GetOptionForName (string option)
  638. {
  639. if (option == null)
  640. throw new ArgumentNullException ("option");
  641. try {
  642. return base [option];
  643. }
  644. catch (KeyNotFoundException) {
  645. return null;
  646. }
  647. }
  648. protected override void InsertItem (int index, Option item)
  649. {
  650. base.InsertItem (index, item);
  651. AddImpl (item);
  652. }
  653. protected override void RemoveItem (int index)
  654. {
  655. Option p = Items [index];
  656. base.RemoveItem (index);
  657. // KeyedCollection.RemoveItem() handles the 0th item
  658. for (int i = 1; i < p.Names.Length; ++i) {
  659. Dictionary.Remove (p.Names [i]);
  660. }
  661. }
  662. protected override void SetItem (int index, Option item)
  663. {
  664. base.SetItem (index, item);
  665. AddImpl (item);
  666. }
  667. private void AddImpl (Option option)
  668. {
  669. if (option == null)
  670. throw new ArgumentNullException ("option");
  671. List<string> added = new List<string> (option.Names.Length);
  672. try {
  673. // KeyedCollection.InsertItem/SetItem handle the 0th name.
  674. for (int i = 1; i < option.Names.Length; ++i) {
  675. Dictionary.Add (option.Names [i], option);
  676. added.Add (option.Names [i]);
  677. }
  678. }
  679. catch (Exception) {
  680. foreach (string name in added)
  681. Dictionary.Remove (name);
  682. throw;
  683. }
  684. }
  685. public OptionSet Add (string header)
  686. {
  687. if (header == null)
  688. throw new ArgumentNullException ("header");
  689. Add (new Category (header));
  690. return this;
  691. }
  692. internal sealed class Category : Option {
  693. // Prototype starts with '=' because this is an invalid prototype
  694. // (see Option.ParsePrototype(), and thus it'll prevent Category
  695. // instances from being accidentally used as normal options.
  696. public Category (string description)
  697. : base ("=:Category:= " + description, description)
  698. {
  699. }
  700. protected override void OnParseComplete (OptionContext c)
  701. {
  702. throw new NotSupportedException ("Category.OnParseComplete should not be invoked.");
  703. }
  704. }
  705. public new OptionSet Add (Option option)
  706. {
  707. base.Add (option);
  708. return this;
  709. }
  710. sealed class ActionOption : Option {
  711. Action<OptionValueCollection> action;
  712. public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action)
  713. : base (prototype, description, count)
  714. {
  715. if (action == null)
  716. throw new ArgumentNullException ("action");
  717. this.action = action;
  718. }
  719. protected override void OnParseComplete (OptionContext c)
  720. {
  721. action (c.OptionValues);
  722. }
  723. }
  724. public OptionSet Add (string prototype, Action<string> action)
  725. {
  726. return Add (prototype, null, action);
  727. }
  728. public OptionSet Add (string prototype, string description, Action<string> action)
  729. {
  730. if (action == null)
  731. throw new ArgumentNullException ("action");
  732. Option p = new ActionOption (prototype, description, 1,
  733. delegate (OptionValueCollection v) { action (v [0]); });
  734. base.Add (p);
  735. return this;
  736. }
  737. public OptionSet Add (string prototype, OptionAction<string, string> action)
  738. {
  739. return Add (prototype, null, action);
  740. }
  741. public OptionSet Add (string prototype, string description, OptionAction<string, string> action)
  742. {
  743. if (action == null)
  744. throw new ArgumentNullException ("action");
  745. Option p = new ActionOption (prototype, description, 2,
  746. delegate (OptionValueCollection v) {action (v [0], v [1]);});
  747. base.Add (p);
  748. return this;
  749. }
  750. sealed class ActionOption<T> : Option {
  751. Action<T> action;
  752. public ActionOption (string prototype, string description, Action<T> action)
  753. : base (prototype, description, 1)
  754. {
  755. if (action == null)
  756. throw new ArgumentNullException ("action");
  757. this.action = action;
  758. }
  759. protected override void OnParseComplete (OptionContext c)
  760. {
  761. action (Parse<T> (c.OptionValues [0], c));
  762. }
  763. }
  764. sealed class ActionOption<TKey, TValue> : Option {
  765. OptionAction<TKey, TValue> action;
  766. public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action)
  767. : base (prototype, description, 2)
  768. {
  769. if (action == null)
  770. throw new ArgumentNullException ("action");
  771. this.action = action;
  772. }
  773. protected override void OnParseComplete (OptionContext c)
  774. {
  775. action (
  776. Parse<TKey> (c.OptionValues [0], c),
  777. Parse<TValue> (c.OptionValues [1], c));
  778. }
  779. }
  780. public OptionSet Add<T> (string prototype, Action<T> action)
  781. {
  782. return Add (prototype, null, action);
  783. }
  784. public OptionSet Add<T> (string prototype, string description, Action<T> action)
  785. {
  786. return Add (new ActionOption<T> (prototype, description, action));
  787. }
  788. public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action)
  789. {
  790. return Add (prototype, null, action);
  791. }
  792. public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action)
  793. {
  794. return Add (new ActionOption<TKey, TValue> (prototype, description, action));
  795. }
  796. public OptionSet Add (ArgumentSource source)
  797. {
  798. if (source == null)
  799. throw new ArgumentNullException ("source");
  800. sources.Add (source);
  801. return this;
  802. }
  803. protected virtual OptionContext CreateOptionContext ()
  804. {
  805. return new OptionContext (this);
  806. }
  807. public List<string> Parse (IEnumerable<string> arguments)
  808. {
  809. if (arguments == null)
  810. throw new ArgumentNullException ("arguments");
  811. OptionContext c = CreateOptionContext ();
  812. c.OptionIndex = -1;
  813. bool process = true;
  814. List<string> unprocessed = new List<string> ();
  815. Option def = Contains ("<>") ? this ["<>"] : null;
  816. ArgumentEnumerator ae = new ArgumentEnumerator (arguments);
  817. foreach (string argument in ae) {
  818. ++c.OptionIndex;
  819. if (argument == "--") {
  820. process = false;
  821. continue;
  822. }
  823. if (!process) {
  824. Unprocessed (unprocessed, def, c, argument);
  825. continue;
  826. }
  827. if (AddSource (ae, argument))
  828. continue;
  829. if (!Parse (argument, c))
  830. Unprocessed (unprocessed, def, c, argument);
  831. }
  832. if (c.Option != null)
  833. c.Option.Invoke (c);
  834. return unprocessed;
  835. }
  836. class ArgumentEnumerator : IEnumerable<string> {
  837. List<IEnumerator<string>> sources = new List<IEnumerator<string>> ();
  838. public ArgumentEnumerator (IEnumerable<string> arguments)
  839. {
  840. sources.Add (arguments.GetEnumerator ());
  841. }
  842. public void Add (IEnumerable<string> arguments)
  843. {
  844. sources.Add (arguments.GetEnumerator ());
  845. }
  846. public IEnumerator<string> GetEnumerator ()
  847. {
  848. do {
  849. IEnumerator<string> c = sources [sources.Count-1];
  850. if (c.MoveNext ())
  851. yield return c.Current;
  852. else {
  853. c.Dispose ();
  854. sources.RemoveAt (sources.Count-1);
  855. }
  856. } while (sources.Count > 0);
  857. }
  858. IEnumerator IEnumerable.GetEnumerator ()
  859. {
  860. return GetEnumerator ();
  861. }
  862. }
  863. bool AddSource (ArgumentEnumerator ae, string argument)
  864. {
  865. foreach (ArgumentSource source in sources) {
  866. IEnumerable<string> replacement;
  867. if (!source.GetArguments (argument, out replacement))
  868. continue;
  869. ae.Add (replacement);
  870. return true;
  871. }
  872. return false;
  873. }
  874. private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument)
  875. {
  876. if (def == null) {
  877. extra.Add (argument);
  878. return false;
  879. }
  880. c.OptionValues.Add (argument);
  881. c.Option = def;
  882. c.Option.Invoke (c);
  883. return false;
  884. }
  885. private readonly Regex ValueOption = new Regex (
  886. @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
  887. protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
  888. {
  889. if (argument == null)
  890. throw new ArgumentNullException ("argument");
  891. flag = name = sep = value = null;
  892. Match m = ValueOption.Match (argument);
  893. if (!m.Success) {
  894. return false;
  895. }
  896. flag = m.Groups ["flag"].Value;
  897. name = m.Groups ["name"].Value;
  898. if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
  899. sep = m.Groups ["sep"].Value;
  900. value = m.Groups ["value"].Value;
  901. }
  902. return true;
  903. }
  904. protected virtual bool Parse (string argument, OptionContext c)
  905. {
  906. if (c.Option != null) {
  907. ParseValue (argument, c);
  908. return true;
  909. }
  910. string f, n, s, v;
  911. if (!GetOptionParts (argument, out f, out n, out s, out v))
  912. return false;
  913. Option p;
  914. if (Contains (n)) {
  915. p = this [n];
  916. c.OptionName = f + n;
  917. c.Option = p;
  918. switch (p.OptionValueType) {
  919. case OptionValueType.None:
  920. c.OptionValues.Add (n);
  921. c.Option.Invoke (c);
  922. break;
  923. case OptionValueType.Optional:
  924. case OptionValueType.Required:
  925. ParseValue (v, c);
  926. break;
  927. }
  928. return true;
  929. }
  930. // no match; is it a bool option?
  931. if (ParseBool (argument, n, c))
  932. return true;
  933. // is it a bundled option?
  934. if (ParseBundledValue (f, string.Concat (n + s + v), c))
  935. return true;
  936. return false;
  937. }
  938. private void ParseValue (string option, OptionContext c)
  939. {
  940. if (option != null)
  941. foreach (string o in c.Option.ValueSeparators != null
  942. ? option.Split (c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
  943. : new string[]{option}) {
  944. c.OptionValues.Add (o);
  945. }
  946. if (c.OptionValues.Count == c.Option.MaxValueCount ||
  947. c.Option.OptionValueType == OptionValueType.Optional)
  948. c.Option.Invoke (c);
  949. else if (c.OptionValues.Count > c.Option.MaxValueCount) {
  950. throw new OptionException (localizer (string.Format (
  951. "Error: Found {0} option values when expecting {1}.",
  952. c.OptionValues.Count, c.Option.MaxValueCount)),
  953. c.OptionName);
  954. }
  955. }
  956. private bool ParseBool (string option, string n, OptionContext c)
  957. {
  958. Option p;
  959. string rn;
  960. if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
  961. Contains ((rn = n.Substring (0, n.Length-1)))) {
  962. p = this [rn];
  963. string v = n [n.Length-1] == '+' ? option : null;
  964. c.OptionName = option;
  965. c.Option = p;
  966. c.OptionValues.Add (v);
  967. p.Invoke (c);
  968. return true;
  969. }
  970. return false;
  971. }
  972. private bool ParseBundledValue (string f, string n, OptionContext c)
  973. {
  974. if (f != "-")
  975. return false;
  976. for (int i = 0; i < n.Length; ++i) {
  977. Option p;
  978. string opt = f + n [i].ToString ();
  979. string rn = n [i].ToString ();
  980. if (!Contains (rn)) {
  981. if (i == 0)
  982. return false;
  983. throw new OptionException (string.Format (localizer (
  984. "Cannot bundle unregistered option '{0}'."), opt), opt);
  985. }
  986. p = this [rn];
  987. switch (p.OptionValueType) {
  988. case OptionValueType.None:
  989. Invoke (c, opt, n, p);
  990. break;
  991. case OptionValueType.Optional:
  992. case OptionValueType.Required: {
  993. string v = n.Substring (i+1);
  994. c.Option = p;
  995. c.OptionName = opt;
  996. ParseValue (v.Length != 0 ? v : null, c);
  997. return true;
  998. }
  999. default:
  1000. throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
  1001. }
  1002. }
  1003. return true;
  1004. }
  1005. private static void Invoke (OptionContext c, string name, string value, Option option)
  1006. {
  1007. c.OptionName = name;
  1008. c.Option = option;
  1009. c.OptionValues.Add (value);
  1010. option.Invoke (c);
  1011. }
  1012. private const int OptionWidth = 29;
  1013. private const int Description_FirstWidth = 80 - OptionWidth;
  1014. private const int Description_RemWidth = 80 - OptionWidth - 2;
  1015. public void WriteOptionDescriptions (TextWriter o)
  1016. {
  1017. foreach (Option p in this) {
  1018. int written = 0;
  1019. Category c = p as Category;
  1020. if (c != null) {
  1021. WriteDescription (o, p.Description, "", 80, 80);
  1022. continue;
  1023. }
  1024. if (!WriteOptionPrototype (o, p, ref written))
  1025. continue;
  1026. if (written < OptionWidth)
  1027. o.Write (new string (' ', OptionWidth - written));
  1028. else {
  1029. o.WriteLine ();
  1030. o.Write (new string (' ', OptionWidth));
  1031. }
  1032. WriteDescription (o, p.Description, new string (' ', OptionWidth+2),
  1033. Description_FirstWidth, Description_RemWidth);
  1034. }
  1035. foreach (ArgumentSource s in sources) {
  1036. string[] names = s.GetNames ();
  1037. if (names == null || names.Length == 0)
  1038. continue;
  1039. int written = 0;
  1040. Write (o, ref written, " ");
  1041. Write (o, ref written, names [0]);
  1042. for (int i = 1; i < names.Length; ++i) {
  1043. Write (o, ref written, ", ");
  1044. Write (o, ref written, names [i]);
  1045. }
  1046. if (written < OptionWidth)
  1047. o.Write (new string (' ', OptionWidth - written));
  1048. else {
  1049. o.WriteLine ();
  1050. o.Write (new string (' ', OptionWidth));
  1051. }
  1052. WriteDescription (o, s.Description, new string (' ', OptionWidth+2),
  1053. Description_FirstWidth, Description_RemWidth);
  1054. }
  1055. }
  1056. void WriteDescription (TextWriter o, string value, string prefix, int firstWidth, int remWidth)
  1057. {
  1058. bool indent = false;
  1059. foreach (string line in GetLines (localizer (GetDescription (value)), firstWidth, remWidth)) {
  1060. if (indent)
  1061. o.Write (prefix);
  1062. o.WriteLine (line);
  1063. indent = true;
  1064. }
  1065. }
  1066. bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
  1067. {
  1068. string[] names = p.Names;
  1069. int i = GetNextOptionIndex (names, 0);
  1070. if (i == names.Length)
  1071. return false;
  1072. if (names [i].Length == 1) {
  1073. Write (o, ref written, " -");
  1074. Write (o, ref written, names [0]);
  1075. }
  1076. else {
  1077. Write (o, ref written, " --");
  1078. Write (o, ref written, names [0]);
  1079. }
  1080. for ( i = GetNextOptionIndex (names, i+1);
  1081. i < names.Length; i = GetNextOptionIndex (names, i+1)) {
  1082. Write (o, ref written, ", ");
  1083. Write (o, ref written, names [i].Length == 1 ? "-" : "--");
  1084. Write (o, ref written, names [i]);
  1085. }
  1086. if (p.OptionValueType == OptionValueType.Optional ||
  1087. p.OptionValueType == OptionValueType.Required) {
  1088. if (p.OptionValueType == OptionValueType.Optional) {
  1089. Write (o, ref written, localizer ("["));
  1090. }
  1091. Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
  1092. string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
  1093. ? p.ValueSeparators [0]
  1094. : " ";
  1095. for (int c = 1; c < p.MaxValueCount; ++c) {
  1096. Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
  1097. }
  1098. if (p.OptionValueType == OptionValueType.Optional) {
  1099. Write (o, ref written, localizer ("]"));
  1100. }
  1101. }
  1102. return true;
  1103. }
  1104. static int GetNextOptionIndex (string[] names, int i)
  1105. {
  1106. while (i < names.Length && names [i] == "<>") {
  1107. ++i;
  1108. }
  1109. return i;
  1110. }
  1111. static void Write (TextWriter o, ref int n, string s)
  1112. {
  1113. n += s.Length;
  1114. o.Write (s);
  1115. }
  1116. private static string GetArgumentName (int index, int maxIndex, string description)
  1117. {
  1118. if (description == null)
  1119. return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
  1120. string[] nameStart;
  1121. if (maxIndex == 1)
  1122. nameStart = new string[]{"{0:", "{"};
  1123. else
  1124. nameStart = new string[]{"{" + index + ":"};
  1125. for (int i = 0; i < nameStart.Length; ++i) {
  1126. int start, j = 0;
  1127. do {
  1128. start = description.IndexOf (nameStart [i], j);
  1129. } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
  1130. if (start == -1)
  1131. continue;
  1132. int end = description.IndexOf ("}", start);
  1133. if (end == -1)
  1134. continue;
  1135. return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
  1136. }
  1137. return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
  1138. }
  1139. private static string GetDescription (string description)
  1140. {
  1141. if (description == null)
  1142. return string.Empty;
  1143. StringBuilder sb = new StringBuilder (description.Length);
  1144. int start = -1;
  1145. for (int i = 0; i < description.Length; ++i) {
  1146. switch (description [i]) {
  1147. case '{':
  1148. if (i == start) {
  1149. sb.Append ('{');
  1150. start = -1;
  1151. }
  1152. else if (start < 0)
  1153. start = i + 1;
  1154. break;
  1155. case '}':
  1156. if (start < 0) {
  1157. if ((i+1) == description.Length || description [i+1] != '}')
  1158. throw new InvalidOperationException ("Invalid option description: " + description);
  1159. ++i;
  1160. sb.Append ("}");
  1161. }
  1162. else {
  1163. sb.Append (description.Substring (start, i - start));
  1164. start = -1;
  1165. }
  1166. break;
  1167. case ':':
  1168. if (start < 0)
  1169. goto default;
  1170. start = i + 1;
  1171. break;
  1172. default:
  1173. if (start < 0)
  1174. sb.Append (description [i]);
  1175. break;
  1176. }
  1177. }
  1178. return sb.ToString ();
  1179. }
  1180. private static IEnumerable<string> GetLines (string description, int firstWidth, int remWidth)
  1181. {
  1182. return StringCoda.WrappedLines (description, firstWidth, remWidth);
  1183. }
  1184. }
  1185. }