4 // Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)
6 // (C) 2002 Rafael Teixeira
10 using System.Collections;
12 using System.Reflection;
14 namespace Mono.GetOptions
18 public enum OptionsParsingMode
28 public class OptionList
31 private Options optionBundle = null;
32 private OptionsParsingMode parsingMode;
33 private bool breakSingleDashManyLettersIntoManyOptions;
34 private bool endOptionProcessingWithDoubleDash;
36 private string appExeName;
37 private string appVersion;
39 private string appTitle = "Add a [assembly: AssemblyTitle(\"Here goes the application name\")] to your assembly";
40 private string appCopyright = "Add a [assembly: AssemblyCopyright(\"(c)200n Here goes the copyright holder name\")] to your assembly";
41 private string appDescription = "Add a [assembly: AssemblyDescription(\"Here goes the short description\")] to your assembly";
42 private string appAboutDetails = "Add a [assembly: Mono.About(\"Here goes the short about details\")] to your assembly";
43 private string appUsageComplement = "Add a [assembly: Mono.UsageComplement(\"Here goes the usage clause complement\")] to your assembly";
44 private string[] appAuthors;
46 private ArrayList list = new ArrayList();
47 private ArrayList arguments = new ArrayList();
48 private ArrayList argumentsTail = new ArrayList();
49 private MethodInfo argumentProcessor = null;
55 return "Usage: " + appExeName + " [options] " + appUsageComplement;
59 public string AboutDetails
63 return appAboutDetails;
67 #region Assembly Attributes
71 private object[] GetAssemblyAttributes(Type type)
73 return entry.GetCustomAttributes(type, false);
76 private string[] GetAssemblyAttributeStrings(Type type)
78 object[] result = GetAssemblyAttributes(type);
80 if ((result == null) || (result.Length == 0))
84 string[] var = new string[result.Length];
86 foreach(object o in result)
87 var[i++] = o.ToString();
92 private void GetAssemblyAttributeValue(Type type, string propertyName, ref string var)
94 object[] result = GetAssemblyAttributes(type);
96 if ((result != null) && (result.Length > 0))
97 var = (string)type.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Instance, null, result[0], new object [] {}); ;
100 private void GetAssemblyAttributeValue(Type type, ref string var)
102 object[] result = GetAssemblyAttributes(type);
104 if ((result != null) && (result.Length > 0))
105 var = result[0].ToString();
112 private void AddArgumentProcessor(MemberInfo memberInfo)
114 if (argumentProcessor != null)
115 throw new NotSupportedException("More than one argument processor method found");
117 if ((memberInfo.MemberType == MemberTypes.Method && memberInfo is MethodInfo))
119 if (((MethodInfo)memberInfo).ReturnType.FullName != typeof(void).FullName)
120 throw new NotSupportedException("Argument processor method must return 'void'");
122 ParameterInfo[] parameters = ((MethodInfo)memberInfo).GetParameters();
123 if ((parameters == null) || (parameters.Length != 1) || (parameters[0].ParameterType.FullName != typeof(string).FullName))
124 throw new NotSupportedException("Argument processor method must have a string parameter");
126 argumentProcessor = (MethodInfo)memberInfo;
129 throw new NotSupportedException("Argument processor marked member isn't a method");
132 private void Initialize(Options optionBundle)
134 if (optionBundle == null)
135 throw new ArgumentNullException("optionBundle");
137 entry = Assembly.GetEntryAssembly();
138 appExeName = entry.GetName().Name;
139 appVersion = entry.GetName().Version.ToString();
141 this.optionBundle = optionBundle;
142 this.parsingMode = optionBundle.ParsingMode ;
143 this.breakSingleDashManyLettersIntoManyOptions = optionBundle.BreakSingleDashManyLettersIntoManyOptions;
144 this.endOptionProcessingWithDoubleDash = optionBundle.EndOptionProcessingWithDoubleDash;
146 GetAssemblyAttributeValue(typeof(AssemblyTitleAttribute), "Title", ref appTitle);
147 GetAssemblyAttributeValue(typeof(AssemblyCopyrightAttribute), "Copyright", ref appCopyright);
148 GetAssemblyAttributeValue(typeof(AssemblyDescriptionAttribute), "Description", ref appDescription);
149 GetAssemblyAttributeValue(typeof(Mono.AboutAttribute), ref appAboutDetails);
150 GetAssemblyAttributeValue(typeof(Mono.UsageComplementAttribute), ref appUsageComplement);
151 appAuthors = GetAssemblyAttributeStrings(typeof(AuthorAttribute));
152 if (appAuthors.Length == 0)
154 appAuthors = new String[1];
155 appAuthors[0] = "Add one or more [assembly: Mono.GetOptions.Author(\"Here goes the author name\")] to your assembly";
158 foreach(MemberInfo mi in optionBundle.GetType().GetMembers())
160 object[] attribs = mi.GetCustomAttributes(typeof(OptionAttribute), true);
161 if (attribs != null && attribs.Length > 0)
162 list.Add(new OptionDetails(mi, (OptionAttribute)attribs[0], optionBundle));
165 attribs = mi.GetCustomAttributes(typeof(ArgumentProcessorAttribute), true);
166 if (attribs != null && attribs.Length > 0)
167 AddArgumentProcessor(mi);
172 public OptionList(Options optionBundle)
174 Initialize(optionBundle);
179 #region Prebuilt Options
181 private void ShowTitleLines()
183 Console.WriteLine(appTitle + " " + appVersion + " - " + appCopyright);
184 Console.WriteLine(appDescription);
188 private void ShowAbout()
191 Console.WriteLine(appAboutDetails);
193 Console.WriteLine("Authors:");
194 foreach(string s in appAuthors)
195 Console.WriteLine ("\t" + s);
198 private void ShowHelp()
201 Console.WriteLine(Usage);
202 Console.WriteLine("Options:");
203 foreach (OptionDetails option in list)
204 Console.WriteLine(option);
207 private void ShowUsage()
209 Console.WriteLine(Usage);
210 Console.Write("Short Options: ");
211 foreach (OptionDetails option in list)
212 Console.Write((option.ShortForm != ' ') ? option.ShortForm.ToString() : "");
217 private void ShowUsage(string errorMessage)
219 Console.WriteLine("ERROR: " + errorMessage.TrimEnd());
223 internal WhatToDoNext DoUsage()
226 return WhatToDoNext.AbandonProgram;
229 internal WhatToDoNext DoAbout()
232 return WhatToDoNext.GoAhead;
235 internal WhatToDoNext DoHelp()
238 return WhatToDoNext.AbandonProgram;
243 #region Arguments Processing
245 public string[] ExpandResponseFiles(string[] args)
247 ArrayList result = new ArrayList();
249 foreach(string arg in args)
251 if (arg.StartsWith("@"))
255 StreamReader tr = new StreamReader(arg.Substring(1));
257 while ((line = tr.ReadLine()) != null)
259 result.AddRange(line.Split());
263 catch (FileNotFoundException exception)
265 Console.WriteLine("Could not find response file: " + arg.Substring(1));
268 catch (Exception exception)
270 Console.WriteLine("Error trying to read response file: " + arg.Substring(1));
271 Console.WriteLine(exception.Message);
279 return (string[])result.ToArray(typeof(string));
282 public string[] NormalizeArgs(string[] args)
284 bool ParsingOptions = true;
285 ArrayList result = new ArrayList();
287 foreach(string arg in ExpandResponseFiles(args))
293 if (endOptionProcessingWithDoubleDash && (arg == "--"))
295 ParsingOptions = false;
301 if ((parsingMode & OptionsParsingMode.Windows) > 0)
303 string newArg = '-' + arg.TrimStart('/');
304 result.AddRange(newArg.Split(':'));
309 if ((parsingMode & OptionsParsingMode.Linux) > 0)
311 if ((arg[0] == '-') && (arg[1] != '-'))
313 if (breakSingleDashManyLettersIntoManyOptions)
315 foreach(char c in arg.Substring(1)) // many single-letter options
316 result.Add("-" + c); // expand into individualized options
323 if (arg.StartsWith("--"))
325 result.AddRange(arg.Split('=')); // put in the same form of one-letter options with a parameter
332 argumentsTail.Add(arg);
336 // if nothing else matches then it get here
341 return (string[])result.ToArray(typeof(string));
344 public string[] ProcessArgs(string[] args)
348 bool OptionWasProcessed;
352 args = NormalizeArgs(args);
356 int argc = args.Length;
357 for (int i = 0; i < argc; i++)
365 OptionWasProcessed = false;
367 if (arg.StartsWith("-"))
369 foreach(OptionDetails option in list)
371 OptionProcessingResult result = option.ProcessArgument(arg, nextArg);
372 if (result != OptionProcessingResult.NotThisOption)
374 OptionWasProcessed = true;
375 if (result == OptionProcessingResult.OptionConsumedParameter)
382 if (!OptionWasProcessed)
384 if (OptionDetails.Verbose)
385 Console.WriteLine("argument [" + arg + "]");
391 foreach(OptionDetails option in list)
392 option.TransferValues();
394 foreach(string argument in argumentsTail)
395 arguments.Add(argument);
397 if (argumentProcessor == null)
398 return (string[])arguments.ToArray(typeof(string));
400 foreach(string argument in arguments)
401 argumentProcessor.Invoke(optionBundle, new object[] { argument });
405 System.Console.WriteLine(ex.ToString());
406 System.Environment.Exit(1);