4 // Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com) (original)
5 // Author: Dean Scarff (D_Scarff@AIMINGFORSPAMFREEmsn.com) (modifications)
7 // (C) 2002 Rafael Teixeira
8 // Modifications (C) 2002 Dean Scarff, distributed under the Gnu General Public License Version 2 or later
12 using System.Collections;
14 using System.Reflection;
16 namespace Mono.GetOptions
20 public enum OptionsParsingMode
30 public class OptionList
33 private Options optionBundle = null;
34 private OptionsParsingMode parsingMode;
35 private bool endOptionProcessingWithDoubleDash;
37 private string appExeName;
38 private string appVersion;
40 private string appTitle = "Add a [assembly: AssemblyTitle(\"Here goes the application name\")] to your assembly";
41 private string appCopyright = "Add a [assembly: AssemblyCopyright(\"(c)200n Here goes the copyright holder name\")] to your assembly";
42 private string appDescription = "Add a [assembly: AssemblyDescription(\"Here goes the short description\")] to your assembly";
43 private string appAboutDetails = "Add a [assembly: Mono.About(\"Here goes the short about details\")] to your assembly";
44 private string appUsageComplement = "Add a [assembly: Mono.UsageComplement(\"Here goes the usage clause complement\")] to your assembly";
45 private string[] appAuthors;
47 private ArrayList list = new ArrayList();
48 private ArrayList arguments = new ArrayList();
49 private ArrayList argumentsTail = new ArrayList();
50 private MethodInfo argumentProcessor = null;
56 return "Usage: " + appExeName + " [options] " + appUsageComplement;
60 public string AboutDetails
64 return appAboutDetails;
68 #region Assembly Attributes
72 private object[] GetAssemblyAttributes(Type type)
74 return entry.GetCustomAttributes(type, false);
77 private string[] GetAssemblyAttributeStrings(Type type)
79 object[] result = GetAssemblyAttributes(type);
81 if ((result == null) || (result.Length == 0))
85 string[] var = new string[result.Length];
87 foreach(object o in result)
88 var[i++] = o.ToString();
93 private void GetAssemblyAttributeValue(Type type, string propertyName, ref string var)
95 object[] result = GetAssemblyAttributes(type);
97 if ((result != null) && (result.Length > 0))
98 var = (string)type.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Instance, null, result[0], new object [] {}); ;
101 private void GetAssemblyAttributeValue(Type type, ref string var)
103 object[] result = GetAssemblyAttributes(type);
105 if ((result != null) && (result.Length > 0))
106 var = result[0].ToString();
113 private void AddArgumentProcessor(MemberInfo memberInfo)
115 if (argumentProcessor != null)
116 throw new NotSupportedException("More than one argument processor method found");
118 if ((memberInfo.MemberType == MemberTypes.Method && memberInfo is MethodInfo))
120 if (((MethodInfo)memberInfo).ReturnType.FullName != typeof(void).FullName)
121 throw new NotSupportedException("Argument processor method must return 'void'");
123 ParameterInfo[] parameters = ((MethodInfo)memberInfo).GetParameters();
124 if ((parameters == null) || (parameters.Length != 1) || (parameters[0].ParameterType.FullName != typeof(string).FullName))
125 throw new NotSupportedException("Argument processor method must have a string parameter");
127 argumentProcessor = (MethodInfo)memberInfo;
130 throw new NotSupportedException("Argument processor marked member isn't a method");
133 private void Initialize(Options optionBundle)
135 if (optionBundle == null)
136 throw new ArgumentNullException("optionBundle");
138 entry = Assembly.GetEntryAssembly();
139 appExeName = entry.GetName().Name;
140 appVersion = entry.GetName().Version.ToString();
142 this.optionBundle = optionBundle;
143 this.parsingMode = optionBundle.ParsingMode ;
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;
299 if ((parsingMode & OptionsParsingMode.Windows) > 0)
301 if ((arg.Length == 2) && (arg[0] == '/')) // Windows options only come in this fashion
303 result.Add("-" + arg[1]); // translate to Linux style
308 if ((parsingMode & OptionsParsingMode.Linux) > 0)
310 if ((arg[0] == '-') && (arg[1] != '-'))
312 foreach(char c in arg.Substring(1)) // many single-letter options
313 result.Add("-" + c); // expand into individualized options
317 if (arg.StartsWith("--"))
319 result.AddRange(arg.Split('=')); // put in the same form of one-letter options with a parameter
326 argumentsTail.Add(arg);
330 // if nothing else matches then it get here
335 return (string[])result.ToArray(typeof(string));
338 public string[] ProcessArgs(string[] args)
342 bool OptionWasProcessed;
346 args = NormalizeArgs(args);
350 int argc = args.Length;
351 for(int i = 0; i < argc; i++)
357 if (nextArg.StartsWith("-"))
363 OptionWasProcessed = false;
365 if (arg.StartsWith("-"))
367 foreach(OptionDetails option in list)
369 if (option.ProcessArgument(arg, nextArg))
371 OptionWasProcessed = true;
379 if (!OptionWasProcessed)
383 foreach(OptionDetails option in list)
384 option.TransferValues();
386 foreach(string argument in argumentsTail)
387 arguments.Add(argument);
389 if (argumentProcessor == null)
390 return (string[])arguments.ToArray(typeof(string));
392 foreach(string argument in arguments)
393 argumentProcessor.Invoke(optionBundle, new object[] { argument });
397 ShowUsage(ex.Message);
398 System.Environment.Exit(1);