2 using System.Collections.Generic;
4 using System.Reflection;
5 using McMaster.Extensions.CommandLineUtils;
24 public static Dictionary<string, object>
Parse(
string applicationName,
string applicationDescription,
string applicationHelpText,
25 string[] args, List<CommandLineOption> options,
bool noArgsShowHelp =
false)
27 var application =
new CommandLineApplication
29 Name = applicationName,
30 Description = applicationDescription,
31 ExtendedHelpText = applicationHelpText
34 application.HelpOption(
"-?|-h|--help");
38 application.VersionOption(
"-v|-V|--version",
40 $
"Version {Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion}");
42 var optionsObject =
new Dictionary<string, object>();
44 var listOfOptions =
new List<CommandOption>();
46 foreach (var option
in options)
48 listOfOptions.Add(application.Option($
"--{option.Name}", option.Description, option.Type));
51 application.OnExecute(() =>
53 foreach (var commandOption
in listOfOptions.Where(option => option.HasValue()))
55 var optionKey = commandOption.Template.Replace(
"--",
"");
56 var matchingOption = options.Find(o => o.Name == optionKey);
57 switch (matchingOption.Type)
60 case CommandOptionType.NoValue:
61 optionsObject[optionKey] = true;
65 case CommandOptionType.SingleValue:
66 optionsObject[optionKey] = commandOption.Value();
70 case CommandOptionType.MultipleValue:
71 var keyValuePairs = commandOption.Value().Split(
',');
72 var subDictionary = new Dictionary<string, string>();
73 foreach (var keyValuePair in keyValuePairs)
75 var subKeys = keyValuePair.Split(
':');
76 subDictionary[subKeys[0]] = subKeys.Length > 1 ? subKeys[1] :
"";
79 optionsObject[optionKey] = subDictionary;
82 throw new ArgumentOutOfRangeException();
89 application.Execute(args);
90 if (noArgsShowHelp && args.Length == 0)
92 application.ShowHelp();
102 if (!
string.IsNullOrEmpty(message))
104 Console.WriteLine(
"\n" + message);
106 Console.WriteLine(
"\nUse the '--help' parameter for more information");
107 Console.WriteLine(
"Press any key to quit");
109 Environment.Exit(exitCode);
115 public static string GetParameterOrExit(IReadOnlyDictionary<string, object> optionsObject,
string parameter)
117 if (!optionsObject.ContainsKey(parameter))
119 PrintMessageAndExit(1,
"ERROR: REQUIRED parameter --" + parameter +
"= is missing");
121 return optionsObject[parameter].ToString();
127 public static string GetParameterOrDefault(IReadOnlyDictionary<string, object> optionsObject,
string parameter,
string defaultValue)
130 if (!optionsObject.TryGetValue(parameter, out value))
132 Console.WriteLine($
"'{parameter}' was not specified. Using default value: '{defaultValue}'");
136 return value.ToString();