/// <summary> /// Parses the command-line arguments. /// </summary> /// <param name="args">The command-line arguments.</param> /// <returns> /// The <see cref="CommandLineCommand"/> object that represents the command that was parsed. /// </returns> public CommandLineCommand Parse(string[] args) { if (args == null || args.Length == 0) { this.PrintUsage(false); return(null); } CommandLineCommand command = this.commands.Find(x => x.Name == args[0]); if (command == null) { this.PrintUsage(false); return(null); } command = command.Parse(this.applicationName, args.Skip(1).ToArray()); if (command?.Name == "help") { this.PrintUsage(command.FindSwitch("long").Exists); return(null); } return(command); }
/// <summary> /// Parses the command-line arguments. /// </summary> /// <param name="prefix">The command prefix that includes application name and parent commands.</param> /// <param name="args">The command-line arguments.</param> /// <returns> /// The parsed <see cref="CommandLineCommand"/>. /// </returns> internal CommandLineCommand Parse(string prefix, string[] args) { if (args.Length == 1 && CommandLineCommand.switchHelp.Parse(args[0])) { goto err; } if (this.commands.Count > 0) { if (args.Length == 0) { goto err; } CommandLineCommand command = this.commands.Find(x => x.Name == args[0]); if (command == null) { goto err; } return(command.Parse(string.Join(" ", prefix, this.Name), args.Skip(1).ToArray())); } else { // parse switches and parameters foreach (CommandLineSwitch @switch in this.options) { bool found = false; for (int i = 0; i < args.Length; i++) { if (@switch.Parse(args[i])) { args.RemoveAt(i); found = true; break; } } if (!found) { if (@switch is CommandLineOption missingParameter && missingParameter.Types.HasFlag(CommandLineOptionTypes.Required)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The parameter <{0}> is required.", missingParameter.Name)); } } } // parse arguments if (args.Length > this.arguments.Count) { goto err; } for (int i = 0; i < args.Length && i < this.arguments.Count; i++) { if (!this.arguments[i].Parse(args[i])) { goto err; } } // validate required arguments CommandLineArgument missingArgument = this.arguments .FirstOrDefault(x => string.IsNullOrEmpty(x.Value) && !x.Types.HasFlag(CommandLineArgumentTypes.Optional)); if (missingArgument != null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The argument <{0}> is required.", missingArgument.Name)); } return(this); } err: this.PrintUsage(prefix); return(null); }