public void Add_NullCommand() { var c = new CommandSet("cs"); Assert.Throws <ArgumentNullException> (() => c.Add((Command)null)); Assert.Throws <ArgumentNullException> (() => c.Add((CommandSet)null)); }
public void Add_DuplicateCommand() { var s = new CommandSet("set"); s.Add(new Command("value")); Assert.Throws <ArgumentException> (() => s.Add(new Command("value"))); }
public static int Main(string[] args) { var commands = new CommandSet("commands") { "usage: commands COMMAND [OPTIONS]", "", "Mono.Options.CommandSet sample app.", "", "Global options:", { "v:", "Output verbosity.", (int?n) => Verbosity = n.HasValue ? n.Value : Verbosity + 1 }, "", "Available commands:", new Command("echo", "Echo arguments to the screen") { Run = ca => Console.WriteLine("{0}", string.Join(" ", ca)), }, new Command("equinox", "Does something with the equinox?") { Run = ca => Console.WriteLine("{0}", string.Join(" ", ca)), }, new RequiresArgsCommand(), "Commands with spaces are supported:", new Command("has spaces", "spaces?!") { Run = ca => Console.WriteLine("spaces, yo! {0}", string.Join(" ", ca)), }, "Nested CommandSets are also supported. They're invoked similarly to commands with spaces.", new CommandSet("set") { new Command("file type", "Does something or other.") { Run = ca => Console.WriteLine("File type set to: {0}", string.Join(" ", ca)), }, new Command("output", "Sets output location") { Run = ca => Console.WriteLine("Output set to: {0}", string.Join(" ", ca)), }, }, }; commands.Add(new Command("completions", "Show CommandSet completions") { Run = ca => { var start = ca.Any() ? string.Join(" ", ca) : ""; Console.WriteLine($"Showing CommandSet completions for prefix '{start}':"); foreach (var completion in commands.GetCompletions(start)) { Console.WriteLine($"\tcompletion: {completion}"); } }, }); commands.Add(commands); return(commands.Run(args)); }
public DebuggerApplication(DebuggerModel model, CommandSet commandSet, CommandResultWriterSet commandResultWriterSet) { this.model = model; this.commandSet = commandSet; this.commandResultWriterSet = commandResultWriterSet; list = new ListCommand(commandSet.GetAll()); commandSet.Add(list); commandSet.Add(new HelpCommand(commandSet)); commandSet.Add(new ConnectCommand()); }
private void PrintAllHelp(CommandSet commandSet, string v) { HelpCommand helpCommand = new HelpCommand(); commandSet.Add(helpCommand); commandSet.Run(new string[] { "help" }); }
private void InitDictionary() { CommandSet.Add(CommandPrintHelp.GetInstance().GetCommand(), CommandPrintHelp.GetInstance()); CommandSet.Add(CommandGenerateSample.GetInstance().GetCommand(), CommandGenerateSample.GetInstance()); CommandSet.Add(CommandCheckJson.GetInstance().GetCommand(), CommandCheckJson.GetInstance()); CommandSet.Add(CommandSolveDesk.GetInstance().GetCommand(), CommandSolveDesk.GetInstance()); CommandSet.Add(CommandQuit.GetInstance().GetCommand(), CommandQuit.GetInstance()); }
public void AddCommand(Command cmd) { if (cmd == null) { Console.WriteLine("Cannot add null command"); return; } CommandSet.Add(cmd); }
public void Add_SetsCommandSet() { var cs = new CommandSet("cs"); var c = new Command("command"); Assert.IsNull(c.CommandSet); cs.Add(c); Assert.AreSame(cs, c.CommandSet); }
public void Add_CommandCanBeAddedToOnlyOneSet() { var cs1 = new CommandSet("cs1"); var cs2 = new CommandSet("cs2"); var c = new Command("command", "help"); cs1.Add(c); Assert.Throws <ArgumentException> (() => cs2.Add(c)); }
protected override ICollection <Command> CreateCollection(IEnumerable <Command> values) { var set = new CommandSet("test"); foreach (var value in values) { set.Add(value); } return(set); }
public static int Main(string[] args) { Console.WriteLine($"XHarness command issued: {string.Join(' ', args)}"); // TODO (#400): We can remove this after some time when users get used to the new commands if (args.Length > 1 && args[0] == "ios") { DisplayRenameWarning(); args[0] = "apple"; } // Root command: will use the platform specific commands to perform the appropriate action. var commands = new CommandSet("xharness"); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { commands.Add(new AppleCommandSet()); } else if (args[0] == "apple") { // Otherwise the command would just not be found Console.Error.WriteLine("The 'apple' command is not available on non-OSX platforms!"); return((int)ExitCode.INVALID_ARGUMENTS); } commands.Add(new AndroidCommandSet()); commands.Add(new WasmCommandSet()); commands.Add(new XHarnessHelpCommand()); commands.Add(new XHarnessVersionCommand()); // Mono.Options wouldn't allow "--" and CommandSet parser will temporarily rename it int result = commands.Run(args.Select(a => a == "--" ? XHarnessCommand.VerbatimArgumentPlaceholder : a)); string?exitCodeName = null; if (result != 0 && Enum.IsDefined(typeof(ExitCode), result)) { exitCodeName = $" ({(ExitCode)result})"; } Console.WriteLine($"XHarness exit code: {result}{exitCodeName}"); return(result); }
public static int Main(string[] args) { Console.WriteLine($"XHarness command issued: {string.Join(' ', args)}"); // Root command: will use the platform specific commands to perform the appropriate action. var commands = new CommandSet("xharness"); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { commands.Add(new iOSCommandSet()); } commands.Add(new AndroidCommandSet()); commands.Add(new WasmCommandSet()); commands.Add(new XHarnessHelpCommand()); commands.Add(new XHarnessVersionCommand()); // Mono.Options wouldn't allow "--" and CommandSet parser will temporarily rename it int result = commands.Run(args.Select(a => a == "--" ? XHarnessCommand.VerbatimArgumentPlaceholder : a)); Console.WriteLine($"XHarness exit code: {result}"); return(result); }
private void CreateHideVesselCommands(CommandSet commands) { var vessels = FlightGlobals.Vessels; for (int i = 0; i < vessels.Count; i++) { var vessel = vessels[i]; var needCommand = m_configuration.HideVesselIcons | m_configuration.HideVesselOrbits; if (needCommand && m_vesselFilter.Accept(vessel)) { var command = new HideOrbitCommand(vessel.orbitRenderer, m_configuration.HideVesselIcons, m_configuration.HideVesselOrbits); commands.Add(command); } } }
private void CreateHideBodiesCommands(CommandSet commands) { var bodies = FlightGlobals.Bodies; for (int i = 0; i < bodies.Count; i++) { var body = bodies[i]; var needCommand = m_configuration.HideCelestialBodyIcons | m_configuration.HideCelestialBodyOrbits; if (needCommand && m_celestialBodyFilter.Accept(body)) { var command = new HideOrbitCommand(body.GetOrbitDriver().Renderer, m_configuration.HideCelestialBodyIcons, m_configuration.HideCelestialBodyOrbits); commands.Add(command); } } }
public static CommandSet GenerateCommandSet(MethodInfo[] methods) { CommandSet commands = new CommandSet(); foreach (MethodInfo method in methods) { CommandAttribute commandAttribute = Attribute.GetCustomAttribute(method, typeof(CommandAttribute), false) as CommandAttribute; if (commandAttribute == null) { continue; } if (string.IsNullOrEmpty(commandAttribute.Name)) { commandAttribute.Name = method.Name; } var overload = new Overload { Description = commandAttribute.Description ?? "", Aliases = commandAttribute.Aliases ?? new string[0], IsHidden = commandAttribute.IsHidden, UseFullDescription = commandAttribute.UseFullDescription, Method = method, }; string commandName = commandAttribute.Name.ToLowerInvariant(); string uuid = commandAttribute.Overload ?? Guid.NewGuid().ToString(); if (commands.ContainsKey(commandName)) { Command command = commands[commandName]; command.Overloads.Add(uuid, overload); } else { commands.Add(commandName, new Command { Name = commandName, Overloads = new Dictionary <string, Overload> { { uuid, overload } } }); } } return(commands); }
static ConCommand() { foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { if (method.IsAbstract || method.DeclaringType != type) { continue; } var attrib = method.GetAttribute <ConCommandAttribute>(false); if (attrib == null) { continue; } try { ConCommandDelegate deleg; if (method.ReturnType == typeof(void)) { var inner = (ConCommandSilentDelegate)Delegate.CreateDelegate(typeof(ConCommandSilentDelegate), method); deleg = args => { inner(args); return(DefaultSuccessString); }; } else { deleg = (ConCommandDelegate)Delegate.CreateDelegate(typeof(ConCommandDelegate), method); } _sRootCommand.Add(attrib.Prefix, deleg, attrib); } catch (ArgumentException) { UnityEngine.Debug.LogWarningFormat("Unable to register {0}.{1} as a console command.", type.FullName, method.Name); } } } }
public IniFile ReadSetting(CommandSet commandSet, string filename) { var file = new IniFile(filename); foreach (var section in file.Sections) { var sectionName = section.Name; var ary = sectionName.Split('_'); sectionName = ary[0]; var name = ary.Length > 1 ? string.Join("_", ary, 1, ary.Length - 1) : null; var setting = SectionSettingMap.Create(sectionName); setting.Id = name; FillProperities(setting, section); var command = CommandSettingMap.Create(setting); commandSet.Add(command); } return file; }
public static int Main(string[] args) { var commands = new CommandSet("commands") { "usage: commands COMMAND [OPTIONS]", "", "Mono.Options.CommandSet sample app.", "", "Global options:", { "v:", "Output verbosity.", (int?n) => Verbosity = n.HasValue ? n.Value : Verbosity + 1 }, "", "Available commands:", new Command("echo", "Echo arguments to the screen") { Run = ca => Console.WriteLine("{0}", string.Join(" ", ca)), }, new RequiresArgsCommand(), "Commands with spaces are supported:", new Command("has spaces", "spaces?!") { Run = ca => Console.WriteLine("spaces, yo! {0}", string.Join(" ", ca)), }, "Nested CommandSets are also supported. They're invoked similarly to commands with spaces.", new CommandSet("set") { new Command("file type", "Does something or other.") { Run = ca => Console.WriteLine("File type set to: {0}", string.Join(" ", ca)), }, }, }; commands.Add(commands); return(commands.Run(args)); }
public static CommandSet GetXHarnessCommandSet() { #pragma warning disable IDE0028 // Simplify collection initialization for DEBUG var commandSet = new CommandSet("xharness"); #pragma warning restore IDE0028 // Simplify collection initialization for DEBUG #if !DEBUG if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { commandSet.Add(new AppleCommandSet()); } #else commandSet.Add(new AppleCommandSet()); #endif commandSet.Add(new AndroidCommandSet()); commandSet.Add(new AndroidHeadlessCommandSet()); commandSet.Add(new WasmCommandSet()); commandSet.Add(new XHarnessHelpCommand()); commandSet.Add(new XHarnessVersionCommand()); return(commandSet); }
private CommandSet GenerateCommandSet(MethodInfo[] methods) { CommandSet commands = new CommandSet(); foreach (MethodInfo method in methods) { CommandAttribute commandAttribute = Attribute.GetCustomAttribute(method, typeof(CommandAttribute), false) as CommandAttribute; if (commandAttribute == null) { continue; } // TODO: Do we need the authorize attribute with the new permission system? AuthorizeAttribute authorizeAttribute = Attribute.GetCustomAttribute(method, typeof(AuthorizeAttribute), false) as AuthorizeAttribute ?? new AuthorizeAttribute(); if (string.IsNullOrEmpty(commandAttribute.Name)) { commandAttribute.Name = method.Name; } var overload = new Overload { Description = commandAttribute.Description ?? "Bullshit", Method = method, Input = new Input(), }; string commandName = commandAttribute.Name.ToLowerInvariant(); var split = commandName.Split(' '); Parameter subCommmandParam = null; if (split.Length > 1) { subCommmandParam = new Parameter(); subCommmandParam.Name = "subcommand"; subCommmandParam.Type = "stringenum"; subCommmandParam.EnumType = "SubCommand" + commandName.Replace(" ", "-"); subCommmandParam.EnumValues = new[] { split[1] }; commandName = split[0]; } if (commands.ContainsKey(commandName)) { Command command = commands[commandName]; command.Versions.First().Overloads.Add(commandAttribute.Overload ?? Guid.NewGuid().ToString(), overload); } else { commands.Add(commandName, new Command { Name = commandName, Versions = new[] { new MiNET.Plugins.Version() { Permission = authorizeAttribute.Permission.ToString().ToLowerInvariant(), CommandPermission = authorizeAttribute.Permission, ErrorMessage = authorizeAttribute.ErrorMessage, Aliases = commandAttribute.Aliases ?? new string[0], Description = commandAttribute.Description ?? "", Overloads = new Dictionary <string, Overload> { { "default", overload }, } }, } }); } List <Parameter> inputParams = new List <Parameter>(); if (subCommmandParam != null) { inputParams.Add(subCommmandParam); } var parameters = method.GetParameters(); bool isFirstParam = true; foreach (var parameter in parameters) { if (isFirstParam && typeof(OpenPlayer).IsAssignableFrom(parameter.ParameterType)) { continue; } isFirstParam = false; if (PluginManager.Services.TryResolve(parameter.ParameterType, out _)) { //This is a depencency injected param continue; } Parameter param = new Parameter(); param.Name = ToCamelCase(parameter.Name); param.Type = GetParameterType(parameter); param.Optional = parameter.IsOptional; if (param.Type.Equals("bool")) { param.Type = "stringenum"; param.EnumType = "bool"; param.EnumValues = new string[] { "false", "true" }; } else if (param.Type.Equals("stringenum")) { if (parameter.ParameterType.IsEnum) { param.EnumValues = parameter.ParameterType.GetEnumNames().Select(s => s.ToLowerInvariant()).ToArray(); string typeName = parameter.ParameterType.Name; typeName = typeName.Replace("Enum", ""); typeName = typeName.ToLowerInvariant()[0] + typeName.Substring(1); param.EnumType = typeName; } else { param.EnumValues = null; string typeName = parameter.ParameterType.Name; typeName = typeName.Replace("Enum", ""); typeName = typeName.ToLowerInvariant()[0] + typeName.Substring(1); param.EnumType = typeName; if (parameter.ParameterType == typeof(ItemTypeEnum)) { param.EnumValues = new string[] { }; param.EnumType = "Item"; } else if (parameter.ParameterType == typeof(BlockTypeEnum)) { param.EnumValues = new string[] { }; param.EnumType = "Block"; } else if (parameter.ParameterType == typeof(EntityTypeEnum)) { param.EnumValues = new string[] { }; param.EnumType = "EntityType"; } else if (parameter.ParameterType == typeof(CommandNameEnum)) { param.EnumValues = new string[] { }; param.EnumType = "CommandName"; } else if (parameter.ParameterType == typeof(EnchantEnum)) { param.EnumValues = new string[] { "enchant_test" }; param.EnumType = "Enchant"; } else if (parameter.ParameterType == typeof(EffectEnum)) { param.EnumValues = new string[] { "effect_test" }; param.EnumType = "Effect"; } else if (typeof(CustomEnum).IsAssignableFrom(parameter.ParameterType)) { CustomEnum c = parameter.ParameterType.GetConstructor(Type.EmptyTypes).Invoke(null) as CustomEnum; if (c != null) { param.EnumValues = c.GetValues(); param.EnumType = c.EnumType; //param.EnumType = c. } } } } inputParams.Add(param); } if (inputParams.Count == 0) { overload.Input.Parameters = null; } else { overload.Input.Parameters = inputParams.ToArray(); } } return(commands); }
/// <summary> /// 通过旅客订座信息和订座的代理人编号,获取订座指令 /// </summary> /// <param name="info">旅客订座信息</param> /// <param name="officeNo">代理人编号</param> /// <returns>指令内容</returns> public static string GetBookInstructionSet(ReservationInfo info, string officeNo) { var commandSet = new CommandSet(); List <string> names = (from n in info.Passengers select n.Name).ToList(); string carrier = info.Segements.First().Carrier; PassengerType passengerType = info.Passengers.First().Type; var firstFlightDate = info.Segements.Min(p => p.Date); // 航段组 foreach (var item in info.Segements) { var ssCommand = new SsCommand(item.Number, item.ClassOfService, item.Date, new AirportPair(item.DepartureAirportCode, item.ArrivalAirportCode), names.Count); commandSet.Add(ssCommand); } // 姓名组,南航的儿童票在特殊服务组中处理; var nmCommand = new NmCommand(names, passengerType, carrier); commandSet.Add(nmCommand); // 联系组(代理人) var ctCommand = new CtCommand(info.AgentPhoneNumber); commandSet.Add(ctCommand); // 特殊服务组(身份证号)和其它服务组(旅客联系方式) int count = 0; foreach (ReservationPassengerInfo passenger in info.Passengers) { var ssrFoidCommand = new SsrCommand(carrier, passenger.CertificateNumber, count + 1, SpecialServiceRequirementType.FOID); commandSet.Add(ssrFoidCommand); // 若不在东航、联合、昆航、上航之列,则按下面的执行,否则只在后面执行一次; if (!(carrier == "MU" || carrier == "FM" || carrier == "KN" || carrier == "KY")) { var osiCommand = new OsiCommand(carrier, passenger.MobilephoneNumber, count + 1, OtherServiceInformationType.CTCT); commandSet.Add(osiCommand); } // 南航儿童票 if (passengerType == PassengerType.Child && carrier.ToUpper() == "CZ") { if (passenger.Birthday == null) { throw new ArgumentNullException(); } var ssrChldCommand = new SsrCommand(carrier, passenger.Birthday.Value.ToString("ddMMMyy", CultureInfo.CreateSpecificCulture("en-US")), count + 1, SpecialServiceRequirementType.CHLD); commandSet.Add(ssrChldCommand); } count++; } // 2013-03-26 根据东航的规定,改成这样; if (carrier == "MU" || carrier == "FM" || carrier == "KN" || carrier == "KY") { // 这里的旅客编号没有用; var osiCommand = new OsiCommand(carrier, info.Passengers[0].MobilephoneNumber, 0, OtherServiceInformationType.CTCT); commandSet.Add(osiCommand); } // 票号组 var tkCommand = new TkCommand(firstFlightDate.AddMinutes(-30), officeNo); commandSet.Add(tkCommand); // 封口指令 var eotCommand = new EotCommand(); commandSet.Add(eotCommand); return(commandSet.CommandString); }
public static CommandSet GenerateCommandSet(MethodInfo[] methods) { CommandSet commands = new CommandSet(); foreach (MethodInfo method in methods) { CommandAttribute commandAttribute = Attribute.GetCustomAttribute(method, typeof(CommandAttribute), false) as CommandAttribute; if (commandAttribute == null) { continue; } AuthorizeAttribute authorizeAttribute = Attribute.GetCustomAttribute(method, typeof(AuthorizeAttribute), false) as AuthorizeAttribute ?? new AuthorizeAttribute(); if (string.IsNullOrEmpty(commandAttribute.Name)) { commandAttribute.Name = method.Name; } var overload = new Overload { Description = commandAttribute.Description, Method = method, Input = new Input(), Output = new Output() { FormatStrings = new[] { new FormatString() { Format = "{0}" }, }, Parameters = new[] { new Parameter { Name = "result", Type = "string" }, } } }; string commandName = commandAttribute.Name.ToLowerInvariant(); if (commands.ContainsKey(commandName)) { Command command = commands[commandName]; command.Versions.First().Overloads.Add(commandAttribute.Overload ?? Guid.NewGuid().ToString(), overload); } else { commands.Add(commandName, new Command { Name = commandName, Versions = new[] { new Version { Permission = authorizeAttribute.Permission.ToString().ToLowerInvariant(), Aliases = commandAttribute.Aliases, Description = commandAttribute.Description, Overloads = new Dictionary <string, Overload> { { "default", overload }, } }, } }); } var parameters = method.GetParameters(); bool isFirstParam = true; List <Parameter> inputParams = new List <Parameter>(); foreach (var parameter in parameters) { if (isFirstParam && typeof(Player).IsAssignableFrom(parameter.ParameterType)) { continue; } isFirstParam = false; Parameter param = new Parameter(); param.Name = ToCamelCase(parameter.Name); param.Type = GetParameterType(parameter); param.Optional = parameter.IsOptional; if (param.Type.Equals("stringenum")) { if (parameter.ParameterType.IsEnum) { param.EnumValues = parameter.ParameterType.GetEnumNames().Select(s => s.ToLowerInvariant()).ToArray(); } else { string typeName = parameter.ParameterType.Name; typeName = typeName.Replace("Enum", ""); typeName = typeName.ToLowerInvariant()[0] + typeName.Substring(1); param.EnumType = typeName; } } inputParams.Add(param); } if (inputParams.Count == 0) { overload.Input.Parameters = null; } else { overload.Input.Parameters = inputParams.ToArray(); } // Output objects if (method.ReturnType != typeof(void)) { var properties = method.ReturnType.GetProperties(BindingFlags.Public | BindingFlags.Instance); List <Parameter> outputParams = new List <Parameter>(); foreach (PropertyInfo property in properties) { if (property.Name.Equals("StatusCode")) { continue; } if (property.Name.Equals("SuccessCount")) { continue; } Parameter param = new Parameter(); param.Name = ToCamelCase(property.Name); param.Type = GetPropertyType(property); outputParams.Add(param); } overload.Output.Parameters = outputParams.ToArray(); } if (commandAttribute.OutputFormatStrings != null) { overload.Output.FormatStrings = new FormatString[commandAttribute.OutputFormatStrings.Length]; int i = 0; foreach (var formatString in commandAttribute.OutputFormatStrings) { overload.Output.FormatStrings[i] = new FormatString() { Format = commandAttribute.OutputFormatStrings[i] }; i++; } } } return(commands); }
public Arguments Parse(string[] args) { var _ = ProgramHelpCommand.HELP_TEXT; var arguments = new Arguments(); void setDirectory(string a) => arguments.Directory = a; void setFormat(string a) => arguments.Format = a; void setRecursive(string a) => arguments.Recursive = a != null; void setJson(string a) => arguments.Json = a != null; void setLog(string a) => arguments.Log = a != null; // Help Command void ShowCommandHelp(Command command) { Console.WriteLine("\nUsage:\n photogrouper {0} {1}\n\nOptions:", command.Name, command.Help); command.Options.WriteOptionDescriptions(Console.Out); // We need to reset the command to now continue after displaying the help text. arguments.Command = ""; } // Executes the run command. void RunCommand(OptionSet options, IEnumerable <string> commandArgs, string command) { arguments.Command = command.ToLower(); try { options.Parse(commandArgs); } catch (OptionException e) { Console.Write("photogrouper: "); Console.WriteLine(e.Message); Console.WriteLine("Try 'photogrouper --help' for more information."); } SetDefaultArguments(arguments); } // Create the Commands var groupCommand = new Command("group", _["group"]); var ungroupCommand = new Command("ungroup", _["ungroup"]); var listCommand = new Command("list", _["list"]); // Create Command Options var groupOptions = new OptionSet() { { "d|directory=", _["directory"], setDirectory }, { "r|recursive", _["recursive"], setRecursive }, { "f|format=", _["format"], setFormat }, { "l|log", _["log"], setLog }, { "h|help", _["help"], (y) => { ShowCommandHelp(groupCommand); } } }; var ungroupOptions = new OptionSet() { { "d|directory=", _["directory"], setDirectory }, { "r|recursive", _["recursive"], setRecursive }, { "l|log", _["log"], setLog }, { "h|help", _["help"], (y) => { ShowCommandHelp(ungroupCommand); } } }; var listOptions = new OptionSet() { { "d|directory=", _["directory"], setDirectory }, { "r|recursive", _["recursive"], setRecursive }, { "j|json", _["json"], setJson }, { "l|log", _["log"], setLog }, { "h|help", _["help"], (y) => { ShowCommandHelp(listCommand); } } }; // Update Command Options groupCommand.Options = groupOptions; groupCommand.Run = commandArgs => RunCommand(groupOptions, commandArgs, "group"); ungroupCommand.Options = ungroupOptions; ungroupCommand.Run = commandArgs => RunCommand(ungroupOptions, commandArgs, "ungroup"); listCommand.Options = listOptions; listCommand.Run = commandArgs => RunCommand(listOptions, commandArgs, "list"); var suite = new CommandSet("photogrouper"); suite.Add(new ProgramHelpCommand()); suite.Add(groupCommand); suite.Add(ungroupCommand); suite.Add(listCommand); //suite.Add(new HelpCommand()); RemoveExtraQuotes(args); suite.Run(args); return(arguments); }
partial void AfterDecode() { CommandSet = new CommandSet(); var stringValues = new List <string>(); { uint count = ReadUnsignedVarInt(); Log.Debug($"String values {count}"); for (int i = 0; i < count; i++) { string str = ReadString(); Log.Debug($"{i} - {str}"); stringValues.Add(str); } } int stringValuesCount = stringValues.Count(); { uint count = ReadUnsignedVarInt(); Log.Debug($"Postfix values {count}"); for (int i = 0; i < count; i++) { string s = ReadString(); Log.Debug(s); } } EnumData[] enums; { uint count = ReadUnsignedVarInt(); enums = new EnumData[count]; Log.Debug($"Enum indexes {count}"); string last = null; string clazzType = null; for (int i = 0; i < count; i++) { string enumName = ReadString(); uint enumValueCount = ReadUnsignedVarInt(); string[] enumValues = new string[enumValueCount]; Log.Debug($"{i} - {enumName}:{enumValueCount}"); for (int j = 0; j < enumValueCount; j++) { int idx; if (stringValuesCount <= byte.MaxValue) { idx = ReadByte(); } else if (stringValuesCount <= short.MaxValue) { idx = ReadShort(); } else { idx = ReadInt(); } enumValues[j] = stringValues[idx]; Log.Debug($"{enumName}, {idx} - {stringValues[idx]}"); } enums[i] = new EnumData(enumName, enumValues); } } { uint count = ReadUnsignedVarInt(); Log.Debug($"Commands definitions {count}"); for (int i = 0; i < count; i++) { Command command = new Command(); command.Versions = new Version[1]; string commandName = ReadString(); string description = ReadString(); int flags = ReadShort(); int permissions = ReadByte(); command.Name = commandName; Version version = new Version(); version.Description = description; int aliasEnumIndex = ReadInt(); uint overloadCount = ReadUnsignedVarInt(); version.Overloads = new Dictionary <string, Overload>(); for (int j = 0; j < overloadCount; j++) { Overload overload = new Overload(); overload.Input = new Input(); uint parameterCount = ReadUnsignedVarInt(); overload.Input.Parameters = new Parameter[parameterCount]; Log.Debug($"{commandName}, {description}, flags={flags}, {((CommandPermission) permissions)}, alias={aliasEnumIndex}, overloads={overloadCount}, params={parameterCount}"); for (int k = 0; k < parameterCount; k++) { string commandParamName = ReadString(); var paramType = ReadInt(); var optional = ReadBool(); var paramFlags = ReadByte(); /*int tmp = ReadShort(); * int tmp1 = ReadShort(); * bool isEnum = (tmp1 & 0x30) == 0x30; * bool isSoftEnum = (tmp1 & 0x0410) == 0x0410; * int commandParamType = -1; * int commandParamEnumIndex = -1; * int commandParamSoftEnumIndex = -1; * int commandParamPostfixIndex = -1; * if ((tmp1 & 0x0030) == 0x0030) * { * commandParamEnumIndex = tmp & 0xffff; * } * else if ((tmp1 & 0x0410) == 0x0410) * { * commandParamType = tmp & 0xffff; * commandParamSoftEnumIndex = tmp & 0xffff; * } * else if ((tmp1 & 0x100) == 0x100) * { * commandParamPostfixIndex = tmp & 0xffff; * } * else if ((tmp1 & 0x10) == 0x10) * { * commandParamType = tmp & 0xffff; * } * else * { * Log.Warn("No parameter style read (enum, valid, postfix)"); * }*/ //bool optional = ReadBool(); //byte unknown = ReadByte(); Parameter parameter = new Parameter() { Name = commandParamName, Optional = optional, Type = GetParameterTypeName((paramType & 0xffff)) }; overload.Input.Parameters[k] = parameter; if ((paramType & 0x200000) != 0) //Enum { var paramEnum = enums[paramType & 0xffff]; parameter.EnumValues = paramEnum.Values; parameter.EnumType = paramEnum.Name; parameter.Type = "stringenum"; } else if ((paramType & 0x1000000) != 0) //Postfix { var paramEnum = enums[paramType & 0xffff]; parameter.EnumValues = paramEnum.Values; parameter.EnumType = paramEnum.Name; parameter.Type = "stringenum"; } //Log.Debug($"\t{commandParamName}, 0x{tmp:X4}, 0x{tmp1:X4}, {isEnum}, {isSoftEnum}, {(GetParameterTypeName(commandParamType))}, {commandParamEnumIndex}, {commandParamSoftEnumIndex}, {commandParamPostfixIndex}, {optional}, {unknown}"); } version.Overloads.Add(j.ToString(), overload); } command.Versions[0] = version; CommandSet.Add(commandName, command); } } { // Soft enums? uint count = ReadUnsignedVarInt(); Log.Debug($"Soft enums {count}"); for (int i = 0; i < count; i++) { string enumName = ReadString(); Log.Debug($"Soft Enum {enumName}"); uint valCount = ReadUnsignedVarInt(); for (int j = 0; j < valCount; j++) { Log.Debug($"\t{enumName} value:{ReadString()}"); } } } { // constraints uint count = ReadUnsignedVarInt(); Log.Debug($"Constraints {count}"); for (int i = 0; i < count; i++) { Log.Debug($"Constraint: {ReadInt()} _ {ReadInt()}"); uint someCount = ReadUnsignedVarInt(); for (int j = 0; j < someCount; j++) { Log.Debug($"\tUnknown byte: {ReadByte()}"); } } } }
static int Main(string [] args) { bool showVersion = false; uint numberOfIds = 1; var firstArg = args.FirstOrDefault(); if (string.IsNullOrEmpty(firstArg) || firstArg [0] == '-' || firstArg [0] == '/') { switch (firstArg?.Substring(1).ToLowerInvariant()) { case "h": case "?": case "help": break; default: args = new [] { "v4" } .Concat(args) .ToArray(); break; } } var suite = new CommandSet("idgen") { { "Usage: idgen COMMAND [OPTIONS]+" }, { "" }, { $" idgen v{version}" }, { $" https://github.com/abock/idgen" }, { $" {copyright}" }, { "" }, { "OPTIONS:" }, { "" }, { "h|?|help", "Show this help.", v => { } }, { "V|version", "Show the idgen version.", v => showVersion = true }, { "n=", "Generate {NUMBER} of identifiers", v => { if (!uint.TryParse(v, out numberOfIds)) { throw new Exception( "NUMBER must be a positive integer, or zero, for the -number option."); } } }, { "" }, { "COMMANDS:" }, { "" } }; var generators = new IIdGenerator [] { new GuidGenerator.V4(), new GuidGenerator.V5(), new GuidGenerator.V3(), new NanoidGenerator(), new HashidsGenerator(), new XcodeIdGenerator() }; foreach (var generator in generators) { var hasOptions = generator.Options?.Any(o => !string.IsNullOrEmpty(o.Prototype)) ?? false; var usageLine = hasOptions ? "[OPTIONS]+" : null; if (!string.IsNullOrEmpty(generator.UsageArguments)) { if (usageLine != null) { usageLine += " "; } usageLine += generator.UsageArguments; } if (usageLine != null) { usageLine = " " + usageLine; } var optionSet = new OptionSet { { $"Usage: {suite.Suite} {generator.Command}{usageLine}" }, }; if (hasOptions) { optionSet.Add(""); optionSet.Add("OPTIONS:"); optionSet.Add(""); foreach (Option option in generator.Options) { optionSet.Add(option); } } suite.Add(new Command(generator.Command, generator.CommandDescription) { Options = optionSet, Run = commandArgs => RunCommand(generator, commandArgs) }); } void RunCommand(IIdGenerator generator, IEnumerable <string> commandArgs) { if (showVersion) { Console.WriteLine(version); return; } for (int i = 0; i < numberOfIds; i++) { Console.WriteLine(generator.Generate(commandArgs)); } } try { suite.Run(args); } catch (Exception e) { Error(e.Message); return(2); } return(0); }
public static int Main(string[] args) { var attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); AssemblyTitle = ((AssemblyTitleAttribute)attributes[0]).Title; attributes = typeof(MainClass).Assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); AssemblyVersion = Attribute.GetCustomAttribute(typeof(MainClass).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; AssemblyCopyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright; DicConsole.WriteLineEvent += System.Console.WriteLine; DicConsole.WriteEvent += System.Console.Write; DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine; Settings.Settings.LoadSettings(); var ctx = DicContext.Create(Settings.Settings.LocalDbPath); ctx.Database.Migrate(); ctx.SaveChanges(); var masterDbUpdate = false; if (!File.Exists(Settings.Settings.MasterDbPath)) { masterDbUpdate = true; UpdateCommand.DoUpdate(true); } var mctx = DicContext.Create(Settings.Settings.MasterDbPath); mctx.Database.Migrate(); mctx.SaveChanges(); if ((args.Length < 1 || args[0].ToLowerInvariant() != "gui") && Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel) { new ConfigureCommand(true, true).Invoke(args); } Statistics.LoadStats(); if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats) { Task.Run(() => { Statistics.SubmitStats(); }); } var currentPlatform = DetectOS.GetRealPlatformID(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var commands = new CommandSet("DiscImageChef") { $"{AssemblyTitle} {AssemblyVersion?.InformationalVersion}", $"{AssemblyCopyright}", "", "usage: DiscImageChef COMMAND [OPTIONS]", "", "Global options:", { "verbose|v", "Shows verbose output.", b => Verbose = b != null }, { "debug|d", "Shows debug output from plugins.", b => Debug = b != null }, "", "Available commands:", new AnalyzeCommand(), new BenchmarkCommand(), new ChecksumCommand(), new CompareCommand(), new ConfigureCommand(false, false), new ConvertImageCommand(), new CreateSidecarCommand(), new DecodeCommand() }; if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux || currentPlatform == PlatformID.Win32NT) { commands.Add(new DeviceInfoCommand()); commands.Add(new DeviceReportCommand()); commands.Add(new DumpMediaCommand()); } commands.Add(new EntropyCommand()); commands.Add(new ExtractFilesCommand()); commands.Add(new FormatsCommand()); commands.Add(new ImageInfoCommand()); if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux || currentPlatform == PlatformID.Win32NT) { commands.Add(new ListDevicesCommand()); } commands.Add(new ListEncodingsCommand()); commands.Add(new ListNamespacesCommand()); commands.Add(new ListOptionsCommand()); commands.Add(new LsCommand()); if (currentPlatform == PlatformID.FreeBSD || currentPlatform == PlatformID.Linux || currentPlatform == PlatformID.Win32NT) { commands.Add(new MediaInfoCommand()); commands.Add(new MediaScanCommand()); } commands.Add(new PrintHexCommand()); commands.Add(new StatisticsCommand()); commands.Add(new UpdateCommand(masterDbUpdate)); commands.Add(new VerifyCommand()); commands.Add(new RemoteCommand()); var ret = commands.Run(args); Statistics.SaveStats(); return(ret); }