PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/MSR.LST/Common/ArgumentParser.cs

#
C# | 90 lines | 67 code | 7 blank | 16 comment | 9 complexity | bbcc004a6fa876621e8bb82b31663fc3 MD5 | raw file
Possible License(s): Apache-2.0, MPL-2.0-no-copyleft-exception
  1. using System;
  2. using System.Collections.Specialized;
  3. using System.Text.RegularExpressions;
  4. namespace MSR.LST
  5. {
  6. /// <summary>
  7. /// Parses command-line arguments into a nice string dictionary to make it easier to work with.
  8. /// </summary>
  9. public class ArgumentParser
  10. {
  11. private StringDictionary arguments;
  12. public ArgumentParser(string[] args)
  13. {
  14. arguments = new StringDictionary();
  15. // Don't break on colons (:) as they are used in IPv6 addresses
  16. Regex splitter = new Regex(@"^-{1,2}|^/|=",RegexOptions.IgnoreCase|RegexOptions.Compiled);
  17. Regex remover = new Regex(@"^['""]?(.*?)['""]?$",RegexOptions.IgnoreCase|RegexOptions.Compiled);
  18. string parameter = null;
  19. string[] parts;
  20. // Valid parameters forms:
  21. // {-,/,--}param{ ,=,:}((",')value(",'))
  22. // Examples: -param1 value1 --param2 /param3:"Test-:-work" /param4=happy -param5 '--=nice=--'
  23. foreach(string arg in args)
  24. {
  25. // Look for new parameters (-,/ or --) and a possible enclosed value (=,:)
  26. parts = splitter.Split(arg,3);
  27. switch(parts.Length)
  28. {
  29. // Found a value (for the last parameter found (space separator))
  30. case 1:
  31. if(parameter!=null)
  32. {
  33. if(!arguments.ContainsKey(parameter))
  34. {
  35. parts[0]=remover.Replace(parts[0],"$1");
  36. arguments.Add(parameter,parts[0]);
  37. }
  38. parameter=null;
  39. }
  40. // else Error: no parameter waiting for a value (skipped)
  41. break;
  42. // Found just a parameter
  43. case 2:
  44. // The last parameter is still waiting. With no value, set it to true.
  45. if(parameter!=null)
  46. {
  47. if(!arguments.ContainsKey(parameter)) arguments.Add(parameter,"true");
  48. }
  49. parameter=parts[1];
  50. break;
  51. // parameter with enclosed value
  52. case 3:
  53. // The last parameter is still waiting. With no value, set it to true.
  54. if(parameter!=null)
  55. {
  56. if(!arguments.ContainsKey(parameter)) arguments.Add(parameter,"true");
  57. }
  58. parameter=parts[1];
  59. // Remove possible enclosing characters (",')
  60. if(!arguments.ContainsKey(parameter))
  61. {
  62. parts[2]=remover.Replace(parts[2],"$1");
  63. arguments.Add(parameter,parts[2]);
  64. }
  65. parameter=null;
  66. break;
  67. }
  68. }
  69. // In case a parameter is still waiting
  70. if(parameter!=null)
  71. {
  72. if(!arguments.ContainsKey(parameter)) arguments.Add(parameter,"true");
  73. }
  74. }
  75. public StringDictionary Parameters
  76. {
  77. get
  78. {
  79. return arguments;
  80. }
  81. }
  82. }
  83. }