/// <summary> /// Parses the command line arguments. /// </summary> /// <param name="arguments">The command line arguments to parse.</param> /// <remarks> /// Parses the command line arguments provided, setting the fields in the object provided when /// this object was instantiated. /// </remarks> private void ParseCommandLine(string[] arguments) { OptionToken token; OptionToken lastToken = null; OptionToken lastOptionToken = null; IOptionParser parser; switch (m_OptionsStyle) { case OptionsStyle.Unix: parser = new UnixOptionParser(arguments); break; case OptionsStyle.Windows: parser = new WindowsOptionEnumerator(arguments); break; default: throw new InternalApplicationException("Unknown command style parser"); } BuildOptionList(parser.LongOptionCaseInsensitive); IOptions options = m_Options as IOptions; if (m_Arguments == null) { m_Arguments = new List <string>(); } try { do { string message; token = parser.GetToken(false); if (token == null) { continue; } switch (token.Token) { case OptionTokenKind.ShortOption: case OptionTokenKind.LongOption: if (m_Arguments.Count > 0) { if (lastOptionToken != null) { message = string.Format("Unexpected option '{0}', perhaps too many arguments after '{1}'", token.ToString(parser), lastOptionToken.ToString(parser)); } else { message = string.Format("Unexpected option '{0}'", token.ToString(parser)); } throw new OptionException(message); } ParseOption(parser, token); lastOptionToken = token; break; case OptionTokenKind.Argument: ParseArgument(token); break; case OptionTokenKind.Value: if (lastToken != null) { message = string.Format("Unexpected value for option {0} (argument {1})", lastToken.ToString(parser), token); throw new OptionException(message); } message = string.Format("Unexpected value {0}", token); throw new OptionException(message); } lastToken = token; } while (token != null); } catch (OptionUnknownException e) { if (options != null) { options.InvalidOption(e.Option); } throw; } catch (OptionMissingArgumentException e) { if (options != null) { options.InvalidOption(e.Option); } throw; } catch (OptionFormatException e) { if (options != null) { options.InvalidOption(e.Option); } throw; } catch (OptionException) { if (options != null) { options.Usage(); } throw; } // Check that all mandatory options were provided StringBuilder sb = new StringBuilder(); List <string> optionList = new List <string>(); foreach (OptionData optionData in m_OptionList) { if (optionData.Attribute.Required && !optionData.Set) { MissingOption(parser, optionData.Attribute.ShortOption, optionData.Attribute.LongOption, sb, optionList); } } if (sb.Length > 0) { if (options != null) { options.Missing(optionList); } throw new OptionMissingException(sb.ToString()); } if (options != null) { options.Check(); } }