CommandLineParser.cs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  1. // **********************************************************************************
  2. // CassiniDev - http://cassinidev.codeplex.com
  3. //
  4. // Copyright (c) 2010 Sky Sanders. All rights reserved.
  5. // Copyright (c) Microsoft Corporation. All rights reserved.
  6. //
  7. // This source code is subject to terms and conditions of the Microsoft Public
  8. // License (Ms-PL). A copy of the license can be found in the license.txt file
  9. // included in this distribution.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // **********************************************************************************
  14. #region
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Diagnostics;
  19. using System.IO;
  20. using System.Reflection;
  21. using System.Text;
  22. using System.Text.RegularExpressions;
  23. #endregion
  24. namespace CassiniDev
  25. {
  26. /// <summary>
  27. /// Parser for command line arguments.
  28. ///
  29. /// The parser specification is infered from the instance fields of the object
  30. /// specified as the destination of the parse.
  31. /// Valid argument types are: int, uint, string, bool, enums
  32. /// Also argument types of Array of the above types are also valid.
  33. ///
  34. /// Error checking options can be controlled by adding a ArgumentAttribute
  35. /// to the instance fields of the destination object.
  36. ///
  37. /// At most one field may be marked with the DefaultArgumentAttribute
  38. /// indicating that arguments without a '-' or '/' prefix will be parsed as that argument.
  39. ///
  40. /// If not specified then the parser will infer default options for parsing each
  41. /// instance field. The default long name of the argument is the field name. The
  42. /// default short name is the first character of the long name. Long names and explicitly
  43. /// specified short names must be unique. Default short names will be used provided that
  44. /// the default short name does not conflict with a long name or an explicitly
  45. /// specified short name.
  46. ///
  47. /// Arguments which are array types are collection arguments. Collection
  48. /// arguments can be specified multiple times.
  49. ///
  50. ///
  51. /// Usage
  52. /// -----
  53. ///
  54. /// Parsing command line arguments to a console application is a common problem.
  55. /// This library handles the common task of reading arguments from a command line
  56. /// and filling in the values in a type.
  57. ///
  58. /// To use this library, define a class whose fields represent the data that your
  59. /// application wants to receive from arguments on the command line. Then call
  60. /// CommandLine.ParseArguments() to fill the object with the data
  61. /// from the command line. Each field in the class defines a command line argument.
  62. /// The type of the field is used to validate the data read from the command line.
  63. /// The name of the field defines the name of the command line option.
  64. ///
  65. /// The parser can handle fields of the following types:
  66. ///
  67. /// - string
  68. /// - int
  69. /// - uint
  70. /// - bool
  71. /// - enum
  72. /// - array of the above type
  73. ///
  74. /// For example, suppose you want to read in the argument list for wc (word count).
  75. /// wc takes three optional boolean arguments: -l, -w, and -c and a list of files.
  76. ///
  77. /// You could parse these arguments using the following code:
  78. ///
  79. /// class WCArguments
  80. /// {
  81. /// public bool lines;
  82. /// public bool words;
  83. /// public bool chars;
  84. /// public string[] files;
  85. /// }
  86. ///
  87. /// class WC
  88. /// {
  89. /// static void Main(string[] args)
  90. /// {
  91. /// if (CommandLine.ParseArgumentsWithUsage(args, parsedArgs))
  92. /// {
  93. /// // insert application code here
  94. /// }
  95. /// }
  96. /// }
  97. ///
  98. /// So you could call this aplication with the following command line to count
  99. /// lines in the foo and bar files:
  100. ///
  101. /// wc.exe /lines /files:foo /files:bar
  102. ///
  103. /// The program will display the following usage message when bad command line
  104. /// arguments are used:
  105. ///
  106. /// wc.exe -x
  107. ///
  108. /// Unrecognized command line argument '-x'
  109. /// /lines[+|-] short form /l
  110. /// /words[+|-] short form /w
  111. /// /chars[+|-] short form /c
  112. /// /files:&lt;string> short form /f
  113. /// @&lt;file> Read response file for more options
  114. ///
  115. /// That was pretty easy. However, you realy want to omit the "/files:" for the
  116. /// list of files. The details of field parsing can be controled using custom
  117. /// attributes. The attributes which control parsing behaviour are:
  118. ///
  119. /// ArgumentAttribute
  120. /// - controls short name, long name, required, allow duplicates, default value
  121. /// and help text
  122. /// DefaultArgumentAttribute
  123. /// - allows omition of the "/name".
  124. /// - This attribute is allowed on only one field in the argument class.
  125. ///
  126. /// So for the wc.exe program we want this:
  127. ///
  128. /// using System;
  129. /// using Utilities;
  130. ///
  131. /// class WCArguments
  132. /// {
  133. /// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of lines in the input text.")]
  134. /// public bool lines;
  135. /// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of words in the input text.")]
  136. /// public bool words;
  137. /// [Argument(ArgumentType.AtMostOnce, HelpText="Count number of chars in the input text.")]
  138. /// public bool chars;
  139. /// [DefaultArgument(ArgumentType.MultipleUnique, HelpText="Input files to count.")]
  140. /// public string[] files;
  141. /// }
  142. ///
  143. /// class WC
  144. /// {
  145. /// static void Main(string[] args)
  146. /// {
  147. /// WCArguments parsedArgs = new WCArguments();
  148. /// if (CommandLine.ParseArgumentsWithUsage(args, parsedArgs))
  149. /// {
  150. /// // insert application code here
  151. /// }
  152. /// }
  153. /// }
  154. ///
  155. ///
  156. ///
  157. /// So now we have the command line we want:
  158. ///
  159. /// wc.exe /lines foo bar
  160. ///
  161. /// This will set lines to true and will set files to an array containing the
  162. /// strings "foo" and "bar".
  163. ///
  164. /// The new usage message becomes:
  165. ///
  166. /// wc.exe -x
  167. ///
  168. /// Unrecognized command line argument '-x'
  169. /// /lines[+|-] Count number of lines in the input text. (short form /l)
  170. /// /words[+|-] Count number of words in the input text. (short form /w)
  171. /// /chars[+|-] Count number of chars in the input text. (short form /c)
  172. /// @&lt;file> Read response file for more options
  173. /// &lt;files> Input files to count. (short form /f)
  174. ///
  175. /// If you want more control over how error messages are reported, how /help is
  176. /// dealt with, etc you can instantiate the CommandLine.Parser class.
  177. ///
  178. ///
  179. ///
  180. /// Cheers,
  181. /// Peter Hallam
  182. /// C# Compiler Developer
  183. /// Microsoft Corp.
  184. ///
  185. ///
  186. ///
  187. ///
  188. /// Release Notes
  189. /// -------------
  190. ///
  191. /// 10/02/2002 Initial Release
  192. /// 10/14/2002 Bug Fix
  193. /// 01/08/2003 Bug Fix in @ include files
  194. /// 10/23/2004 Added user specified help text, formatting of help text to
  195. /// screen width. Added ParseHelp for /?.
  196. /// 11/23/2004 Added support for default values.
  197. /// 02/23/2005 Fix bug with short name and default arguments.
  198. ///
  199. /// 12/24/2009 sky: Added ushort as valid argument type.
  200. /// 12/27/2009 sky: todo: expose out and err to enable use in forms app.
  201. /// 12/29/2009 sky: added ArgumentsAttribute and GetGenericUsageString to allow attaching generic help text
  202. /// 01/01/2010 sky: split classes into seperate files
  203. /// 01/01/2010 sky: cleaned up Parser.cs
  204. /// 05/22/2010 sky: major cleanup - more to come.
  205. /// </summary>
  206. public sealed class CommandLineParser
  207. {
  208. /// <summary>
  209. /// The System Defined new line string.
  210. /// </summary>
  211. public const string NewLine = "\r\n";
  212. private const int SpaceBeforeParam = 2;
  213. private const int StdOutputHandle = -11;
  214. private readonly Hashtable _argumentMap;
  215. private readonly ArrayList _arguments;
  216. private readonly Type _argumentSpecification;
  217. private readonly Argument _defaultArgument;
  218. private readonly ErrorReporter _reporter;
  219. /// <summary>
  220. /// Don't ever call this.
  221. /// </summary>
  222. // ReSharper disable UnusedMember.Local
  223. private CommandLineParser()
  224. // ReSharper restore UnusedMember.Local
  225. {
  226. //noop
  227. }
  228. /// <summary>
  229. /// Creates a new command line argument parser.
  230. /// </summary>
  231. /// <param name="argumentSpecification"> The type of object to parse. </param>
  232. /// <param name="reporter"> The destination for parse errors. </param>
  233. public CommandLineParser(Type argumentSpecification, ErrorReporter reporter)
  234. {
  235. _argumentSpecification = argumentSpecification;
  236. _reporter = reporter;
  237. _arguments = new ArrayList();
  238. _argumentMap = new Hashtable();
  239. foreach (FieldInfo field in argumentSpecification.GetFields())
  240. {
  241. if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral)
  242. {
  243. ArgumentAttribute attribute = GetAttribute(field);
  244. if (attribute is DefaultArgumentAttribute)
  245. {
  246. Debug.Assert(_defaultArgument == null);
  247. _defaultArgument = new Argument(attribute, field, reporter);
  248. }
  249. else
  250. {
  251. _arguments.Add(new Argument(attribute, field, reporter));
  252. }
  253. }
  254. }
  255. // add explicit names to map
  256. foreach (Argument argument in _arguments)
  257. {
  258. Debug.Assert(!_argumentMap.ContainsKey(argument.LongName));
  259. _argumentMap[argument.LongName] = argument;
  260. if (argument.ExplicitShortName)
  261. {
  262. if (!string.IsNullOrEmpty(argument.ShortName))
  263. {
  264. Debug.Assert(!_argumentMap.ContainsKey(argument.ShortName));
  265. _argumentMap[argument.ShortName] = argument;
  266. }
  267. else
  268. {
  269. argument.ClearShortName();
  270. }
  271. }
  272. }
  273. // add implicit names which don't collide to map
  274. foreach (Argument argument in _arguments)
  275. {
  276. if (!argument.ExplicitShortName)
  277. {
  278. if (!string.IsNullOrEmpty(argument.ShortName) && !_argumentMap.ContainsKey(argument.ShortName))
  279. _argumentMap[argument.ShortName] = argument;
  280. else
  281. argument.ClearShortName();
  282. }
  283. }
  284. }
  285. /// <summary>
  286. /// Does this parser have a default argument.
  287. /// </summary>
  288. /// <value> Does this parser have a default argument. </value>
  289. public bool HasDefaultArgument
  290. {
  291. get { return _defaultArgument != null; }
  292. }
  293. /// <summary>
  294. /// Returns a Usage string for command line argument parsing.
  295. /// Use ArgumentAttributes to control parsing behaviour.
  296. /// Formats the output to the width of the current console window.
  297. /// </summary>
  298. /// <param name="argumentType"> The type of the arguments to display usage for. </param>
  299. /// <returns> Printable string containing a user friendly description of command line arguments. </returns>
  300. public static string ArgumentsUsage(Type argumentType)
  301. {
  302. int screenWidth = GetConsoleWindowWidth();
  303. if (screenWidth == 0)
  304. screenWidth = 80;
  305. return ArgumentsUsage(argumentType, screenWidth);
  306. }
  307. /// <summary>
  308. /// Returns a Usage string for command line argument parsing.
  309. /// Use ArgumentAttributes to control parsing behaviour.
  310. /// </summary>
  311. /// <param name="argumentType"> The type of the arguments to display usage for. </param>
  312. /// <param name="columns"> The number of columns to format the output to. </param>
  313. /// <returns> Printable string containing a user friendly description of command line arguments. </returns>
  314. public static string ArgumentsUsage(Type argumentType, int columns)
  315. {
  316. return (new CommandLineParser(argumentType, null)).GetUsageString(columns);
  317. }
  318. /// <summary>
  319. /// Returns the number of columns in the current console window
  320. /// </summary>
  321. /// <returns>Returns the number of columns in the current console window</returns>
  322. public static int GetConsoleWindowWidth()
  323. {
  324. Interop.CONSOLE_SCREEN_BUFFER_INFO csbi = new Interop.CONSOLE_SCREEN_BUFFER_INFO();
  325. #pragma warning disable 168
  326. int rc = Interop.GetConsoleScreenBufferInfo(Interop.GetStdHandle(StdOutputHandle), ref csbi);
  327. #pragma warning restore 168
  328. int screenWidth = csbi.dwSize.x;
  329. return screenWidth;
  330. }
  331. /// <summary>
  332. /// A user firendly usage string describing the command line argument syntax.
  333. /// </summary>
  334. public string GetUsageString(int screenWidth)
  335. {
  336. ArgumentHelpStrings[] strings = GetAllHelpStrings();
  337. int maxParamLen = 0;
  338. foreach (ArgumentHelpStrings helpString in strings)
  339. {
  340. maxParamLen = Math.Max(maxParamLen, helpString.syntax.Length);
  341. }
  342. const int minimumNumberOfCharsForHelpText = 10;
  343. const int minimumHelpTextColumn = 5;
  344. const int minimumScreenWidth = minimumHelpTextColumn + minimumNumberOfCharsForHelpText;
  345. int idealMinimumHelpTextColumn = maxParamLen + SpaceBeforeParam;
  346. screenWidth = Math.Max(screenWidth, minimumScreenWidth);
  347. int helpTextColumn = screenWidth < (idealMinimumHelpTextColumn + minimumNumberOfCharsForHelpText)
  348. ? minimumHelpTextColumn
  349. : idealMinimumHelpTextColumn;
  350. const string newLine = "\n";
  351. StringBuilder builder = new StringBuilder();
  352. // 01/01/2010 sky
  353. string genericUsage = GetGenericUsageString(_argumentSpecification, screenWidth);
  354. if (!string.IsNullOrEmpty(genericUsage))
  355. {
  356. builder.AppendLine(genericUsage);
  357. }
  358. foreach (ArgumentHelpStrings helpStrings in strings)
  359. {
  360. // add syntax string
  361. int syntaxLength = helpStrings.syntax.Length;
  362. builder.Append(helpStrings.syntax);
  363. // start help text on new line if syntax string is too long
  364. int currentColumn = syntaxLength;
  365. if (syntaxLength >= helpTextColumn)
  366. {
  367. builder.Append(newLine);
  368. currentColumn = 0;
  369. }
  370. // add help text broken on spaces
  371. int charsPerLine = screenWidth - helpTextColumn;
  372. int index = 0;
  373. while (index < helpStrings.help.Length)
  374. {
  375. // tab to start column
  376. builder.Append(' ', helpTextColumn - currentColumn);
  377. currentColumn = helpTextColumn;
  378. // find number of chars to display on this line
  379. int endIndex = index + charsPerLine;
  380. if (endIndex >= helpStrings.help.Length)
  381. {
  382. // rest of text fits on this line
  383. endIndex = helpStrings.help.Length;
  384. }
  385. else
  386. {
  387. endIndex = helpStrings.help.LastIndexOf(' ', endIndex - 1,
  388. Math.Min(endIndex - index, charsPerLine));
  389. if (endIndex <= index)
  390. {
  391. // no spaces on this line, append full set of chars
  392. endIndex = index + charsPerLine;
  393. }
  394. }
  395. // add chars
  396. builder.Append(helpStrings.help, index, endIndex - index);
  397. index = endIndex;
  398. // do new line
  399. AddNewLine(newLine, builder, ref currentColumn);
  400. // don't start a new line with spaces
  401. while (index < helpStrings.help.Length && helpStrings.help[index] == ' ')
  402. index++;
  403. }
  404. // add newline if there's no help text
  405. if (helpStrings.help.Length == 0)
  406. {
  407. builder.Append(newLine);
  408. }
  409. }
  410. return builder.ToString();
  411. }
  412. /// <summary>
  413. /// Searches a StringBuilder for a character
  414. /// </summary>
  415. /// <param name="text"> The text to search. </param>
  416. /// <param name="value"> The character value to search for. </param>
  417. /// <param name="startIndex"> The index to stat searching at. </param>
  418. /// <returns> The index of the first occurence of value or -1 if it is not found. </returns>
  419. public static int IndexOf(StringBuilder text, char value, int startIndex)
  420. {
  421. for (int index = startIndex; index < text.Length; index++)
  422. {
  423. if (text[index] == value)
  424. return index;
  425. }
  426. return -1;
  427. }
  428. /// <summary>
  429. /// Searches a StringBuilder for a character in reverse
  430. /// </summary>
  431. /// <param name="text"> The text to search. </param>
  432. /// <param name="value"> The character to search for. </param>
  433. /// <param name="startIndex"> The index to start the search at. </param>
  434. /// <returns>The index of the last occurence of value in text or -1 if it is not found. </returns>
  435. public static int LastIndexOf(StringBuilder text, char value, int startIndex)
  436. {
  437. for (int index = Math.Min(startIndex, text.Length - 1); index >= 0; index--)
  438. {
  439. if (text[index] == value)
  440. return index;
  441. }
  442. return -1;
  443. }
  444. /// <summary>
  445. /// Parses an argument list.
  446. /// </summary>
  447. /// <param name="args"> The arguments to parse. </param>
  448. /// <param name="destination"> The destination of the parsed arguments. </param>
  449. /// <returns> true if no parse errors were encountered. </returns>
  450. public bool Parse(string[] args, object destination)
  451. {
  452. bool hadError = ParseArgumentList(args, destination);
  453. // check for missing required arguments
  454. foreach (Argument arg in _arguments)
  455. {
  456. hadError |= arg.Finish(destination);
  457. }
  458. if (_defaultArgument != null)
  459. {
  460. hadError |= _defaultArgument.Finish(destination);
  461. }
  462. return !hadError;
  463. }
  464. /// <summary>
  465. /// Parses Command Line Arguments.
  466. /// Errors are output on Console.Error.
  467. /// Use ArgumentAttributes to control parsing behaviour.
  468. /// </summary>
  469. /// <param name="arguments"> The actual arguments. </param>
  470. /// <param name="destination"> The resulting parsed arguments. </param>
  471. /// <returns> true if no errors were detected. </returns>
  472. public static bool ParseArguments(string[] arguments, object destination)
  473. {
  474. return ParseArguments(arguments, destination, Console.Error.WriteLine);
  475. }
  476. /// <summary>
  477. /// Parses Command Line Arguments.
  478. /// Use ArgumentAttributes to control parsing behaviour.
  479. /// </summary>
  480. /// <param name="arguments"> The actual arguments. </param>
  481. /// <param name="destination"> The resulting parsed arguments. </param>
  482. /// <param name="reporter"> The destination for parse errors. </param>
  483. /// <returns> true if no errors were detected. </returns>
  484. public static bool ParseArguments(string[] arguments, object destination, ErrorReporter reporter)
  485. {
  486. CommandLineParser parser = new CommandLineParser(destination.GetType(), reporter);
  487. return parser.Parse(arguments, destination);
  488. }
  489. /// <summary>
  490. /// Parses Command Line Arguments. Displays usage message to Console.Out
  491. /// if /?, /help or invalid arguments are encounterd.
  492. /// Errors are output on Console.Error.
  493. /// Use ArgumentAttributes to control parsing behaviour.
  494. /// </summary>
  495. /// <param name="arguments"> The actual arguments. </param>
  496. /// <param name="destination"> The resulting parsed arguments. </param>
  497. /// <returns> true if no errors were detected. </returns>
  498. public static bool ParseArgumentsWithUsage(string[] arguments, object destination)
  499. {
  500. if (ParseHelp(arguments) || !ParseArguments(arguments, destination))
  501. {
  502. // error encountered in arguments. Display usage message
  503. Console.Write(ArgumentsUsage(destination.GetType()));
  504. return false;
  505. }
  506. return true;
  507. }
  508. /// <summary>
  509. /// Checks if a set of arguments asks for help.
  510. /// </summary>
  511. /// <param name="args"> Args to check for help. </param>
  512. /// <returns> Returns true if args contains /? or /help. </returns>
  513. public static bool ParseHelp(string[] args)
  514. {
  515. CommandLineParser helpParser = new CommandLineParser(typeof (HelpArgument), NullErrorReporter);
  516. HelpArgument helpArgument = new HelpArgument();
  517. helpParser.Parse(args, helpArgument);
  518. return helpArgument.help;
  519. }
  520. private static void AddNewLine(string newLine, StringBuilder builder, ref int currentColumn)
  521. {
  522. builder.Append(newLine);
  523. currentColumn = 0;
  524. }
  525. private static object DefaultValue(ArgumentAttribute attribute)
  526. {
  527. return (attribute == null || !attribute.HasDefaultValue) ? null : attribute.DefaultValue;
  528. }
  529. private static Type ElementType(FieldInfo field)
  530. {
  531. return IsCollectionType(field.FieldType) ? field.FieldType.GetElementType() : null;
  532. }
  533. private static bool ExplicitShortName(ArgumentAttribute attribute)
  534. {
  535. return (attribute != null && !attribute.DefaultShortName);
  536. }
  537. private static ArgumentType Flags(ArgumentAttribute attribute, FieldInfo field)
  538. {
  539. if (attribute != null)
  540. {
  541. return attribute.Type;
  542. }
  543. return IsCollectionType(field.FieldType) ? ArgumentType.MultipleUnique : ArgumentType.AtMostOnce;
  544. }
  545. private ArgumentHelpStrings[] GetAllHelpStrings()
  546. {
  547. ArgumentHelpStrings[] strings = new ArgumentHelpStrings[NumberOfParametersToDisplay()];
  548. int index = 0;
  549. foreach (Argument arg in _arguments)
  550. {
  551. strings[index] = GetHelpStrings(arg);
  552. index++;
  553. }
  554. strings[index++] = new ArgumentHelpStrings("@<file>", "Read response file for more options");
  555. if (_defaultArgument != null)
  556. {
  557. strings[index] = GetHelpStrings(_defaultArgument);
  558. }
  559. return strings;
  560. }
  561. private static ArgumentAttribute GetAttribute(ICustomAttributeProvider field)
  562. {
  563. object[] attributes = field.GetCustomAttributes(typeof (ArgumentAttribute), false);
  564. if (attributes.Length == 1)
  565. return (ArgumentAttribute) attributes[0];
  566. Debug.Assert(attributes.Length == 0);
  567. return null;
  568. }
  569. /// <summary>
  570. /// 01/01/2010 sky
  571. /// </summary>
  572. private static string GetGenericUsageString(ICustomAttributeProvider type, int cols)
  573. {
  574. object[] attributes = type.GetCustomAttributes(typeof (ArgumentsAttribute), true);
  575. if (attributes.Length == 0 || !((ArgumentsAttribute) attributes[0]).HasHelpText)
  576. {
  577. return string.Empty;
  578. }
  579. StringBuilder sb = new StringBuilder();
  580. string usage = ((ArgumentsAttribute) attributes[0]).HelpText;
  581. // simple width formatter
  582. string[] lines = Regex.Split(usage, Environment.NewLine);
  583. foreach (string line in lines)
  584. {
  585. string[] words = Regex.Split(line, " ");
  586. string currentLine = string.Empty;
  587. foreach (string word in words)
  588. {
  589. if (currentLine.Length + word.Length + 1 > cols)
  590. {
  591. // start new line
  592. sb.AppendLine(currentLine);
  593. currentLine = word + " ";
  594. }
  595. else
  596. {
  597. currentLine += (word + " ");
  598. }
  599. }
  600. sb.AppendLine(currentLine);
  601. sb.Append(Environment.NewLine);
  602. }
  603. return sb.ToString();
  604. }
  605. private static ArgumentHelpStrings GetHelpStrings(Argument arg)
  606. {
  607. return new ArgumentHelpStrings(arg.SyntaxHelp, arg.FullHelpText);
  608. }
  609. private static bool HasHelpText(ArgumentAttribute attribute)
  610. {
  611. return (attribute != null && attribute.HasHelpText);
  612. }
  613. private static string HelpText(ArgumentAttribute attribute)
  614. {
  615. return attribute == null ? null : attribute.HelpText;
  616. }
  617. private static bool IsCollectionType(Type type)
  618. {
  619. return type.IsArray;
  620. }
  621. private static bool IsValidElementType(Type type)
  622. {
  623. //SKY:12/25/09 - added ushort
  624. return type != null && (
  625. type == typeof (int) ||
  626. type == typeof (uint) ||
  627. type == typeof (ushort) ||
  628. type == typeof (string) ||
  629. type == typeof (bool) ||
  630. type.IsEnum);
  631. }
  632. private bool LexFileArguments(string fileName, out string[] argumentsOut)
  633. {
  634. string args;
  635. try
  636. {
  637. using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  638. {
  639. args = (new StreamReader(file)).ReadToEnd();
  640. }
  641. }
  642. catch (Exception e)
  643. {
  644. _reporter(string.Format("Error: Can't open command line argument file '{0}' : '{1}'", fileName,
  645. e.Message));
  646. argumentsOut = null;
  647. return false;
  648. }
  649. bool hadError = false;
  650. ArrayList argArray = new ArrayList();
  651. StringBuilder currentArg = new StringBuilder();
  652. bool inQuotes = false;
  653. int index = 0;
  654. // while (index < args.Length)
  655. try
  656. {
  657. while (true)
  658. {
  659. // skip whitespace
  660. while (char.IsWhiteSpace(args[index]))
  661. {
  662. index += 1;
  663. }
  664. // # - comment to end of line
  665. if (args[index] == '#')
  666. {
  667. index += 1;
  668. while (args[index] != '\n')
  669. {
  670. index += 1;
  671. }
  672. continue;
  673. }
  674. // do one argument
  675. do
  676. {
  677. if (args[index] == '\\')
  678. {
  679. int cSlashes = 1;
  680. index += 1;
  681. while (index == args.Length && args[index] == '\\')
  682. {
  683. cSlashes += 1;
  684. }
  685. if (index == args.Length || args[index] != '"')
  686. {
  687. currentArg.Append('\\', cSlashes);
  688. }
  689. else
  690. {
  691. currentArg.Append('\\', (cSlashes >> 1));
  692. if (0 != (cSlashes & 1))
  693. {
  694. currentArg.Append('"');
  695. }
  696. else
  697. {
  698. inQuotes = !inQuotes;
  699. }
  700. }
  701. }
  702. else if (args[index] == '"')
  703. {
  704. inQuotes = !inQuotes;
  705. index += 1;
  706. }
  707. else
  708. {
  709. currentArg.Append(args[index]);
  710. index += 1;
  711. }
  712. } while (!char.IsWhiteSpace(args[index]) || inQuotes);
  713. argArray.Add(currentArg.ToString());
  714. currentArg.Length = 0;
  715. }
  716. }
  717. catch (IndexOutOfRangeException)
  718. {
  719. // got EOF
  720. if (inQuotes)
  721. {
  722. _reporter(string.Format("Error: Unbalanced '\"' in command line argument file '{0}'", fileName));
  723. hadError = true;
  724. }
  725. else if (currentArg.Length > 0)
  726. {
  727. // valid argument can be terminated by EOF
  728. argArray.Add(currentArg.ToString());
  729. }
  730. }
  731. argumentsOut = (string[]) argArray.ToArray(typeof (string));
  732. return hadError;
  733. }
  734. private static string LongName(ArgumentAttribute attribute, FieldInfo field)
  735. {
  736. return (attribute == null || attribute.DefaultLongName) ? field.Name : attribute.LongName;
  737. }
  738. private static void NullErrorReporter(string message)
  739. {
  740. }
  741. private int NumberOfParametersToDisplay()
  742. {
  743. int numberOfParameters = _arguments.Count + 1;
  744. if (HasDefaultArgument)
  745. {
  746. numberOfParameters += 1;
  747. }
  748. return numberOfParameters;
  749. }
  750. /// <summary>
  751. /// Parses an argument list into an object
  752. /// </summary>
  753. /// <param name="args"></param>
  754. /// <param name="destination"></param>
  755. /// <returns> true if an error occurred </returns>
  756. private bool ParseArgumentList(IEnumerable<string> args, object destination)
  757. {
  758. bool hadError = false;
  759. if (args != null)
  760. {
  761. foreach (string argument in args)
  762. {
  763. if (argument.Length > 0)
  764. {
  765. switch (argument[0])
  766. {
  767. case '-':
  768. case '/':
  769. int endIndex = argument.IndexOfAny(new[] {':', '+', '-'}, 1);
  770. string option = argument.Substring(1,
  771. endIndex == -1 ? argument.Length - 1 : endIndex - 1);
  772. string optionArgument;
  773. if (option.Length + 1 == argument.Length)
  774. {
  775. optionArgument = null;
  776. }
  777. else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':')
  778. {
  779. optionArgument = argument.Substring(option.Length + 2);
  780. }
  781. else
  782. {
  783. optionArgument = argument.Substring(option.Length + 1);
  784. }
  785. Argument arg = (Argument) _argumentMap[option];
  786. if (arg == null)
  787. {
  788. ReportUnrecognizedArgument(argument);
  789. hadError = true;
  790. }
  791. else
  792. {
  793. hadError |= !arg.SetValue(optionArgument, destination);
  794. }
  795. break;
  796. case '@':
  797. string[] nestedArguments;
  798. hadError |= LexFileArguments(argument.Substring(1), out nestedArguments);
  799. hadError |= ParseArgumentList(nestedArguments, destination);
  800. break;
  801. default:
  802. if (_defaultArgument != null)
  803. {
  804. hadError |= !_defaultArgument.SetValue(argument, destination);
  805. }
  806. else
  807. {
  808. ReportUnrecognizedArgument(argument);
  809. hadError = true;
  810. }
  811. break;
  812. }
  813. }
  814. }
  815. }
  816. return hadError;
  817. }
  818. private void ReportUnrecognizedArgument(string argument)
  819. {
  820. _reporter(string.Format("Unrecognized command line argument '{0}'", argument));
  821. }
  822. private static string ShortName(ArgumentAttribute attribute, FieldInfo field)
  823. {
  824. if (attribute is DefaultArgumentAttribute)
  825. return null;
  826. if (!ExplicitShortName(attribute))
  827. return LongName(attribute, field).Substring(0, 1);
  828. return attribute.ShortName;
  829. }
  830. #region Nested type: Argument
  831. [DebuggerDisplay("Name = {LongName}")]
  832. private class Argument
  833. {
  834. private readonly ArrayList _collectionValues;
  835. private readonly object _defaultValue;
  836. private readonly Type _elementType;
  837. private readonly bool _explicitShortName;
  838. private readonly FieldInfo _field;
  839. private readonly ArgumentType _flags;
  840. private readonly bool _hasHelpText;
  841. private readonly string _helpText;
  842. private readonly bool _isDefault;
  843. private readonly string _longName;
  844. private readonly ErrorReporter _reporter;
  845. private bool _seenValue;
  846. private string _shortName;
  847. public Argument(ArgumentAttribute attribute, FieldInfo field, ErrorReporter reporter)
  848. {
  849. _longName = CommandLineParser.LongName(attribute, field);
  850. _explicitShortName = CommandLineParser.ExplicitShortName(attribute);
  851. _shortName = CommandLineParser.ShortName(attribute, field);
  852. _hasHelpText = CommandLineParser.HasHelpText(attribute);
  853. _helpText = CommandLineParser.HelpText(attribute);
  854. _defaultValue = CommandLineParser.DefaultValue(attribute);
  855. _elementType = ElementType(field);
  856. _flags = Flags(attribute, field);
  857. _field = field;
  858. _seenValue = false;
  859. _reporter = reporter;
  860. _isDefault = attribute != null && attribute is DefaultArgumentAttribute;
  861. if (IsCollection)
  862. {
  863. _collectionValues = new ArrayList();
  864. }
  865. Debug.Assert(!string.IsNullOrEmpty(_longName));
  866. Debug.Assert(!_isDefault || !ExplicitShortName);
  867. Debug.Assert(!IsCollection || AllowMultiple, "Collection arguments must have allow multiple");
  868. Debug.Assert(!Unique || IsCollection, "Unique only applicable to collection arguments");
  869. Debug.Assert(IsValidElementType(Type) || IsCollectionType(Type));
  870. Debug.Assert((IsCollection && IsValidElementType(_elementType)) ||
  871. (!IsCollection && _elementType == null));
  872. Debug.Assert(!(IsRequired && HasDefaultValue), "Required arguments cannot have default value");
  873. Debug.Assert(!HasDefaultValue || (_defaultValue.GetType() == field.FieldType),
  874. "Type of default value must match field type");
  875. }
  876. private Type ValueType
  877. {
  878. get { return IsCollection ? _elementType : Type; }
  879. }
  880. public string LongName
  881. {
  882. get { return _longName; }
  883. }
  884. public bool ExplicitShortName
  885. {
  886. get { return _explicitShortName; }
  887. }
  888. public string ShortName
  889. {
  890. get { return _shortName; }
  891. }
  892. private bool HasShortName
  893. {
  894. get { return _shortName != null; }
  895. }
  896. private bool HasHelpText
  897. {
  898. get { return _hasHelpText; }
  899. }
  900. private string HelpText
  901. {
  902. get { return _helpText; }
  903. }
  904. private object DefaultValue
  905. {
  906. get { return _defaultValue; }
  907. }
  908. private bool HasDefaultValue
  909. {
  910. get { return null != _defaultValue; }
  911. }
  912. public string FullHelpText
  913. {
  914. get
  915. {
  916. StringBuilder builder = new StringBuilder();
  917. if (HasHelpText)
  918. {
  919. builder.Append(HelpText);
  920. }
  921. if (HasDefaultValue)
  922. {
  923. if (builder.Length > 0)
  924. builder.Append(" ");
  925. builder.Append("Default value:'");
  926. AppendValue(builder, DefaultValue);
  927. builder.Append('\'');
  928. }
  929. if (HasShortName)
  930. {
  931. if (builder.Length > 0)
  932. builder.Append(" ");
  933. builder.Append("(short form /");
  934. builder.Append(ShortName);
  935. builder.Append(")");
  936. }
  937. return builder.ToString();
  938. }
  939. }
  940. public string SyntaxHelp
  941. {
  942. get
  943. {
  944. StringBuilder builder = new StringBuilder();
  945. if (IsDefault)
  946. {
  947. builder.Append("<");
  948. builder.Append(LongName);
  949. builder.Append(">");
  950. }
  951. else
  952. {
  953. builder.Append("/");
  954. builder.Append(LongName);
  955. Type valueType = ValueType;
  956. if (valueType == typeof (int))
  957. {
  958. builder.Append(":<int>");
  959. }
  960. else if (valueType == typeof (uint))
  961. {
  962. builder.Append(":<uint>");
  963. }
  964. else if (valueType == typeof (bool))
  965. {
  966. builder.Append("[+|-]");
  967. }
  968. else if (valueType == typeof (string))
  969. {
  970. builder.Append(":<string>");
  971. }
  972. else
  973. {
  974. Debug.Assert(valueType.IsEnum);
  975. builder.Append(":{");
  976. bool first = true;
  977. foreach (FieldInfo info in valueType.GetFields())
  978. {
  979. if (info.IsStatic)
  980. {
  981. if (first)
  982. first = false;
  983. else
  984. builder.Append('|');
  985. builder.Append(info.Name);
  986. }
  987. }
  988. builder.Append('}');
  989. }
  990. }
  991. return builder.ToString();
  992. }
  993. }
  994. private bool IsRequired
  995. {
  996. get { return 0 != (_flags & ArgumentType.Required); }
  997. }
  998. private bool SeenValue
  999. {
  1000. get { return _seenValue; }
  1001. }
  1002. private bool AllowMultiple
  1003. {
  1004. get { return 0 != (_flags & ArgumentType.Multiple); }
  1005. }
  1006. private bool Unique
  1007. {
  1008. get { return 0 != (_flags & ArgumentType.Unique); }
  1009. }
  1010. private Type Type
  1011. {
  1012. get { return _field.FieldType; }
  1013. }
  1014. private bool IsCollection
  1015. {
  1016. get { return IsCollectionType(Type); }
  1017. }
  1018. private bool IsDefault
  1019. {
  1020. get { return _isDefault; }
  1021. }
  1022. public bool Finish(object destination)
  1023. {
  1024. if (SeenValue)
  1025. {
  1026. if (IsCollection)
  1027. {
  1028. _field.SetValue(destination, _collectionValues.ToArray(_elementType));
  1029. }
  1030. }
  1031. else
  1032. {
  1033. if (HasDefaultValue)
  1034. {
  1035. _field.SetValue(destination, DefaultValue);
  1036. }
  1037. }
  1038. return ReportMissingRequiredArgument();
  1039. }
  1040. private bool ReportMissingRequiredArgument()
  1041. {
  1042. if (IsRequired && !SeenValue)
  1043. {
  1044. if (IsDefault)
  1045. _reporter(string.Format("Missing required argument '<{0}>'.", LongName));
  1046. else
  1047. _reporter(string.Format("Missing required argument '/{0}'.", LongName));
  1048. return true;
  1049. }
  1050. return false;
  1051. }
  1052. private void ReportDuplicateArgumentValue(string value)
  1053. {
  1054. _reporter(string.Format("Duplicate '{0}' argument '{1}'", LongName, value));
  1055. }
  1056. public bool SetValue(string value, object destination)
  1057. {
  1058. if (SeenValue && !AllowMultiple)
  1059. {
  1060. _reporter(string.Format("Duplicate '{0}' argument", LongName));
  1061. return false;
  1062. }
  1063. _seenValue = true;
  1064. object newValue;
  1065. if (!ParseValue(ValueType, value, out newValue))
  1066. {
  1067. return false;
  1068. }
  1069. if (IsCollection)
  1070. {
  1071. if (Unique && _collectionValues.Contains(newValue))
  1072. {
  1073. ReportDuplicateArgumentValue(value);
  1074. return false;
  1075. }
  1076. _collectionValues.Add(newValue);
  1077. }
  1078. else
  1079. {
  1080. _field.SetValue(destination, newValue);
  1081. }
  1082. return true;
  1083. }
  1084. private void ReportBadArgumentValue(string value)
  1085. {
  1086. _reporter(string.Format("'{0}' is not a valid value for the '{1}' command line option", value, LongName));
  1087. }
  1088. private bool ParseValue(Type type, string stringData, out object value)
  1089. {
  1090. // null is only valid for bool variables
  1091. // empty string is never valid
  1092. if (!string.IsNullOrEmpty(stringData) || type == typeof (bool))
  1093. {
  1094. try
  1095. {
  1096. do //omed loop
  1097. {
  1098. if (type == typeof (string))
  1099. {
  1100. value = stringData;
  1101. return true;
  1102. }
  1103. if (type == typeof (bool))
  1104. {
  1105. if (stringData == null || stringData == "+")
  1106. {
  1107. value = true;
  1108. return true;
  1109. }
  1110. if (stringData == "-")
  1111. {
  1112. value = false;
  1113. return true;
  1114. }
  1115. break;
  1116. }
  1117. // from this point on, a null or empty string is invalid
  1118. if (string.IsNullOrEmpty(stringData))
  1119. {
  1120. break;
  1121. }
  1122. if (type == typeof (int))
  1123. {
  1124. value = int.Parse(stringData);
  1125. return true;
  1126. }
  1127. if (type == typeof (uint))
  1128. {
  1129. value = int.Parse(stringData);
  1130. return true;
  1131. }
  1132. //SKY:12/25/09 - added ushort
  1133. if (type == typeof (ushort))
  1134. {
  1135. value = ushort.Parse(stringData);
  1136. return true;
  1137. }
  1138. Debug.Assert(type.IsEnum);
  1139. bool valid = false;
  1140. foreach (string name in Enum.GetNames(type))
  1141. {
  1142. if (string.Compare(name, stringData, StringComparison.InvariantCultureIgnoreCase) == 0)
  1143. {
  1144. valid = true;
  1145. break;
  1146. }
  1147. }
  1148. if (valid)
  1149. {
  1150. value = Enum.Parse(type, stringData, true);
  1151. return true;
  1152. }
  1153. } while (false);
  1154. }
  1155. // ReSharper disable EmptyGeneralCatchClause
  1156. catch
  1157. // ReSharper restore EmptyGeneralCatchClause
  1158. {
  1159. // catch parse errors
  1160. }
  1161. }
  1162. ReportBadArgumentValue(stringData);
  1163. value = null;
  1164. return false;
  1165. }
  1166. private static void AppendValue(StringBuilder builder, object value)
  1167. {
  1168. //SKY:12/25/09 - add ushort
  1169. if (value is string || value is int || value is uint || value is ushort || value.GetType().IsEnum)
  1170. {
  1171. builder.Append(value.ToString());
  1172. }
  1173. else if (value is bool)
  1174. {
  1175. builder.Append((bool) value ? "+" : "-");
  1176. }
  1177. else
  1178. {
  1179. bool first = true;
  1180. foreach (object o in (Array) value)
  1181. {
  1182. if (!first)
  1183. {
  1184. builder.Append(", ");
  1185. }
  1186. AppendValue(builder, o);
  1187. first = false;
  1188. }
  1189. }
  1190. }
  1191. public void ClearShortName()
  1192. {
  1193. _shortName = null;
  1194. }
  1195. }
  1196. #endregion
  1197. #region Nested type: ArgumentHelpStrings
  1198. private struct ArgumentHelpStrings
  1199. {
  1200. public readonly string help;
  1201. public readonly string syntax;
  1202. public ArgumentHelpStrings(string syntax, string help)
  1203. {
  1204. this.syntax = syntax;
  1205. this.help = help;
  1206. }
  1207. }
  1208. #endregion
  1209. #region Nested type: HelpArgument
  1210. private class HelpArgument
  1211. {
  1212. [Argument(ArgumentType.AtMostOnce, ShortName = "?")] public bool help;
  1213. }
  1214. #endregion
  1215. }
  1216. /// <summary>
  1217. /// A delegate used in error reporting.
  1218. /// </summary>
  1219. public delegate void ErrorReporter(string message);
  1220. /// <summary>
  1221. /// Indicates that this argument is the default argument.
  1222. /// '/' or '-' prefix only the argument value is specified.
  1223. /// The ShortName property should not be set for DefaultArgumentAttribute
  1224. /// instances. The LongName property is used for usage text only and
  1225. /// does not affect the usage of the argument.
  1226. /// </summary>
  1227. [AttributeUsage(AttributeTargets.Field)]
  1228. public class DefaultArgumentAttribute : ArgumentAttribute
  1229. {
  1230. /// <summary>
  1231. /// Indicates that this argument is the default argument.
  1232. /// </summary>
  1233. /// <param name="type"> Specifies the error checking to be done on the argument. </param>
  1234. public DefaultArgumentAttribute(ArgumentType type)
  1235. : base(type)
  1236. {
  1237. }
  1238. }
  1239. /// <summary>
  1240. /// Used to control parsing of command line arguments.
  1241. /// </summary>
  1242. [Flags]
  1243. public enum ArgumentType
  1244. {
  1245. /// <summary>
  1246. /// Indicates that this field is required. An error will be displayed
  1247. /// if it is not present when parsing arguments.
  1248. /// </summary>
  1249. Required = 0x01,
  1250. /// <summary>
  1251. /// Only valid in conjunction with Multiple.
  1252. /// Duplicate values will result in an error.
  1253. /// </summary>
  1254. Unique = 0x02,
  1255. /// <summary>
  1256. /// Inidicates that the argument may be specified more than once.
  1257. /// Only valid if the argument is a collection
  1258. /// </summary>
  1259. Multiple = 0x04,
  1260. /// <summary>
  1261. /// The default type for non-collection arguments.
  1262. /// The argument is not required, but an error will be reported if it is specified more than once.
  1263. /// </summary>
  1264. AtMostOnce = 0x00,
  1265. /// <summary>
  1266. /// For non-collection arguments, when the argument is specified more than
  1267. /// once no error is reported and the value of the argument is the last
  1268. /// value which occurs in the argument list.
  1269. /// </summary>
  1270. LastOccurenceWins = Multiple,
  1271. /// <summary>
  1272. /// The default type for collection arguments.
  1273. /// The argument is permitted to occur multiple times, but duplicate
  1274. /// values will cause an error to be reported.
  1275. /// </summary>
  1276. MultipleUnique = Multiple | Unique,
  1277. }
  1278. /// <summary>
  1279. /// Allows attaching generic help text to arguments class
  1280. ///
  1281. /// 12/29/09 sky: added
  1282. /// </summary>
  1283. [AttributeUsage(AttributeTargets.Class)]
  1284. public class ArgumentsAttribute : Attribute
  1285. {
  1286. private string _helpText;
  1287. /// <summary>
  1288. /// Returns true if the argument has help text specified.
  1289. /// </summary>
  1290. public bool HasHelpText
  1291. {
  1292. get { return null != _helpText; }
  1293. }
  1294. /// <summary>
  1295. /// The help text for the argument.
  1296. /// </summary>
  1297. public string HelpText
  1298. {
  1299. get { return _helpText; }
  1300. set { _helpText = value; }
  1301. }
  1302. }
  1303. /// <summary>
  1304. /// Allows control of command line parsing.
  1305. /// Attach this attribute to instance fields of types used
  1306. /// as the destination of command line argument parsing.
  1307. /// </summary>
  1308. [AttributeUsage(AttributeTargets.Field)]
  1309. public class ArgumentAttribute : Attribute
  1310. {
  1311. #region Fields
  1312. private readonly ArgumentType _type;
  1313. private object _defaultValue;
  1314. private string _helpText;
  1315. private string _longName;
  1316. private string _shortName;
  1317. #endregion
  1318. #region Constructors
  1319. /// <summary>
  1320. /// Allows control of command line parsing.
  1321. /// </summary>
  1322. /// <param name="type"> Specifies the error checking to be done on the argument. </param>
  1323. public ArgumentAttribute(ArgumentType type)
  1324. {
  1325. _type = type;
  1326. }
  1327. #endregion
  1328. #region Properties
  1329. /// <summary>
  1330. /// Returns true if the argument did not have an explicit long name specified.
  1331. /// </summary>
  1332. public bool DefaultLongName
  1333. {
  1334. get { return null == _longName; }
  1335. }
  1336. /// <summary>
  1337. /// Returns true if the argument did not have an explicit short name specified.
  1338. /// </summary>
  1339. public bool DefaultShortName
  1340. {
  1341. get { return null == _shortName; }
  1342. }
  1343. /// <summary>
  1344. /// The default value of the argument.
  1345. /// </summary>
  1346. public object DefaultValue
  1347. {
  1348. get { return _defaultValue; }
  1349. set { _defaultValue = value; }
  1350. }
  1351. /// <summary>
  1352. /// Returns true if the argument has a default value.
  1353. /// </summary>
  1354. public bool HasDefaultValue
  1355. {
  1356. get { return null != _defaultValue; }
  1357. }
  1358. /// <summary>
  1359. /// Returns true if the argument has help text specified.
  1360. /// </summary>
  1361. public bool HasHelpText
  1362. {
  1363. get { return null != _helpText; }
  1364. }
  1365. /// <summary>
  1366. /// The help text for the argument.
  1367. /// </summary>
  1368. public string HelpText
  1369. {
  1370. get { return _helpText; }
  1371. set { _helpText = value; }
  1372. }
  1373. /// <summary>
  1374. /// The long name of the argument.
  1375. /// Set to null means use the default long name.
  1376. /// The long name for every argument must be unique.
  1377. /// It is an error to specify a long name of String.Empty.
  1378. /// </summary>
  1379. public string LongName
  1380. {
  1381. get
  1382. {
  1383. Debug.Assert(!DefaultLongName);
  1384. return _longName;
  1385. }
  1386. set
  1387. {
  1388. Debug.Assert(value != "");
  1389. _longName = value;
  1390. }
  1391. }
  1392. /// <summary>
  1393. /// The short name of the argument.
  1394. /// Set to null means use the default short name if it does not
  1395. /// conflict with any other parameter name.
  1396. /// Set to String.Empty for no short name.
  1397. /// This property should not be set for DefaultArgumentAttributes.
  1398. /// </summary>
  1399. public string ShortName
  1400. {
  1401. get { return _shortName; }
  1402. set
  1403. {
  1404. Debug.Assert(value == null || !(this is DefaultArgumentAttribute));
  1405. _shortName = value;
  1406. }
  1407. }
  1408. /// <summary>
  1409. /// The error checking to be done on the argument.
  1410. /// </summary>
  1411. public ArgumentType Type
  1412. {
  1413. get { return _type; }
  1414. }
  1415. #endregion
  1416. }
  1417. }