public void Command_ArgumentResult_Parent_is_set_correctly_when_token_is_implicit() { ArgumentResult argumentResult = null; var command = new Command("the-command") { new Argument <string>( parse: argResult => { argumentResult = argResult; return(null); }, isDefault: true) }; command.Parse(""); argumentResult .Parent .Symbol .Should() .Be(command); }
// parse List<string> command line arg (--files) private static List <string> ParseStringList(ArgumentResult result) { string name = result.Parent?.Symbol.Name.ToUpperInvariant().Replace('-', '_'); if (string.IsNullOrEmpty(name)) { result.ErrorMessage = "result.Parent is null"; return(null); } List <string> val = new List <string>(); if (result.Tokens.Count == 0) { string env = Environment.GetEnvironmentVariable(name); if (string.IsNullOrWhiteSpace(env)) { result.ErrorMessage = $"--{result.Argument.Name} is a required parameter"; return(null); } string[] files = env.Split(' ', StringSplitOptions.RemoveEmptyEntries); foreach (string f in files) { val.Add(f.Trim()); } } else { for (int i = 0; i < result.Tokens.Count; i++) { val.Add(result.Tokens[i].Value.Trim()); } } return(val); }
/// <summary> /// Validates that the specified argument result is found and has an expected file extension. /// </summary> private static void ValidateArgumentValueIsExpectedFile(ArgumentResult result, params string[] extensions) { string fileName = result.GetValueOrDefault <string>(); string foundExtension = Path.GetExtension(fileName); if (!extensions.Any(extension => extension == foundExtension)) { if (extensions.Length is 1) { result.ErrorMessage = $"File '{fileName}' does not have the expected '{extensions[0]}' extension."; } else { result.ErrorMessage = $"File '{fileName}' does not have one of the expected extensions: " + $"{string.Join(", ", extensions)}."; } } else if (!File.Exists(fileName)) { result.ErrorMessage = $"File '{fileName}' does not exist."; } }
public void Option_ArgumentResult_Parent_is_set_correctly_when_token_is_implicit() { ArgumentResult argumentResult = null; var command = new Command("the-command") { new Option <string>( "-x", parseArgument: argResult => { argumentResult = argResult; return(null); }, isDefault: true) }; command.Parse(""); argumentResult .Parent .Symbol .Should() .Be(command.Options.Single()); }
public static IEnumerable <FileInfo> ParseWildcards(ArgumentResult result) { foreach (var token in result.Tokens) { var location = token.Value; if (location.IndexOfAny(IOHelpers.Wildcards) < 0) { yield return(new FileInfo(location)); } else { var directory = Path.GetDirectoryName(location); if (directory.Length == 0) { directory = Directory.GetCurrentDirectory(); } var name = Path.GetFileName(location); foreach (var item in Directory.EnumerateFiles(directory, name)) { yield return(new FileInfo(item)); } } } }
public static Task <int> Main(string[] args) { #if !NOCODEPAGES Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); #endif // !NOCODEPAGES var cliParser = new CommandLineBuilder(RootCommand()) .UseDefaults() .UseMiddleware(async(invokeCtx, next) => { var cts = new CancellationTokenSource(); var onCancelKeyPress = new ConsoleCancelEventHandler((object senter, ConsoleCancelEventArgs e) => { // If cancellation already has been requested, // do not cancel process termination signal. e.Cancel = !cts.IsCancellationRequested; cts.Cancel(throwOnFirstException: true); }); Console.CancelKeyPress += onCancelKeyPress; invokeCtx.BindingContext.AddService(typeof(CancellationTokenSource), () => cts); invokeCtx.BindingContext.AddService(typeof(CancellationToken), () => cts.Token); try { await next(invokeCtx).ConfigureAwait(false); } catch (OperationCanceledException) { } finally { Console.CancelKeyPress -= onCancelKeyPress; } }) .Build(); return(cliParser.InvokeAsync(args ?? Array.Empty <string>())); RootCommand RootCommand() { var root = new RootCommand(description); root.AddOption(new Option( new string[] { "-d", "--decode" }, "decode data (encodes by default)", new Argument <bool>() )); root.AddOption(new Option( new string[] { "-i", "--ignore-garbage" }, "when decoding, ignore non-alphabet characters", new Argument <bool>() )); root.AddOption(new Option( new string[] { "-w", "--wrap" }, "wrap encoded lines after COLS characters (default 76). Use 0 to disable line wrapping", WrapArgument() )); root.AddOption(new Option( new string[] { "-f", "--file" }, "Encode or decode contents of FILE ('-' for STDIN)", FileArgument() )); root.AddOption(new Option( new string[] { "-c", "--charset" }, $"use CHARSET when decoding data from a file (Default: {Encoding.UTF8.WebName}).", CharsetArgument() )); root.AddOption(new Option( new string[] { "-b", "--buffer" }, "use SIZE as the read-buffer size. (Default: 4096)", new Argument <int>(4096) { Name = "SIZE", Description = "Size to use for intermediate read buffer" } )); root.Handler = CommandHandler.Create(typeof(Program).GetMethod(nameof(InvokeAsync))); return(root); Argument <int?> WrapArgument() { var arg = new Argument <int?>(symbol => { if (symbol.Arguments.FirstOrDefault().TryNotNull(out string value)) { try { int number = int.Parse(value, NumberStyles.Integer, CultureInfo.CurrentCulture); return(ArgumentResult.Success <int?>(number)); } catch (OverflowException overflowExcept) { return(ArgumentResult.Failure(overflowExcept.Message)); } catch (FormatException formatExcept) { return(ArgumentResult.Failure(formatExcept.Message)); } } return(ArgumentResult.Success <int?>(76)); }) { Name = "COLS", Description = $"Number of characters per line (default {76})", Arity = ArgumentArity.ZeroOrOne }; arg.SetDefaultValue(null); arg.AddValidator(symbol => symbol.Arguments.Select(s => { if (int.TryParse(s, NumberStyles.Any, CultureInfo.CurrentCulture, out int v) && v >= 0) { return(null); } return($"Argument '{s}' for option '{symbol.Token}' is invalid. Expected a non-negative integer value."); }).Where(msg => !string.IsNullOrWhiteSpace(msg)).FirstOrDefault()); return(arg); } Argument <FileInfo> FileArgument() { var argument = new Argument <FileInfo> { Name = "FILE", Description = "Path to read from or write to", Arity = ArgumentArity.ExactlyOne }; argument.AddValidator(symbol => { IEnumerable <string> source = from filePath in symbol.Arguments where !filePath.Equals("-", StringComparison.Ordinal) where !File.Exists(filePath) select filePath; ValidationMessages validationMessages = symbol.ValidationMessages; return(source.Select(validationMessages.FileDoesNotExist).FirstOrDefault()); }); return(argument); } Argument <Encoding> CharsetArgument() { var arg = new Argument <Encoding>(ConvertToEncoding) { Arity = ArgumentArity.ZeroOrOne, Name = "CHARSET", Description = $"IANA charset name (default: {Encoding.UTF8})" }; arg.AddSuggestions(Encoding.GetEncodings().Select(enc => enc.Name).ToArray()); arg.SetDefaultValue(Encoding.UTF8); return(arg); ArgumentResult ConvertToEncoding(SymbolResult symbol) { if (symbol.Arguments.FirstOrDefault().TryNotNullOrWhiteSpace(out string charset)) { try { var encoding = Encoding.GetEncoding(charset); return(ArgumentResult.Success(encoding)); } catch (ArgumentException) { return(ArgumentResult.Failure($"Argument '{charset}' for option '{symbol.Token}' is invalid. '{charset}' is not a supported encoding name.")); } } return(ArgumentResult.Success(Encoding.UTF8)); } } } }
public override void Process() { Logger.Log(LogType.Log, $"Running CL Kernel: {Kernel.Name}", MIN_INSTRUCTION_SEVERITY); ArgumentResult[] results = new ArgumentResult[Arguments.Count]; Logger.Log( LogType.Log, $"[{Kernel.Name}]Computing Kernel Arguments", MIN_INSTRUCTION_SEVERITY ); for (int i = 0; i < Arguments.Count; i++) { results[i] = Compute(Arguments[i]); } for (int i = 0; i < results.Length; i++) { Logger.Log( LogType.Log, $"[{Kernel.Name}]Setting Kernel Argument {Kernel.Parameter.First(x => x.Value.Id == i)}", MIN_INSTRUCTION_SEVERITY + 1 ); int kernelArgIndex = i + FL_HEADER_ARG_COUNT; ArgumentResult arg = results[i]; switch (arg.Type) { case FLInstructionArgumentType.Number: Kernel.SetArg(kernelArgIndex, arg.Value); //The Value is a Decimal break; case FLInstructionArgumentType.Buffer: FLBuffer bi = (FLBuffer)arg.Value; Logger.Log( LogType.Log, $"[{Kernel.Name}]Argument Buffer{bi.DefinedBufferName}", MIN_INSTRUCTION_SEVERITY + 2 ); Kernel.SetBuffer(kernelArgIndex, bi.Buffer); break; case FLInstructionArgumentType.Function: FLBuffer funcBuffer = (FLBuffer)arg.Value; Logger.Log( LogType.Log, $"[{Kernel.Name}]Argument Buffer{funcBuffer.DefinedBufferName}", MIN_INSTRUCTION_SEVERITY + 2 ); Kernel.SetBuffer(kernelArgIndex, funcBuffer.Buffer); break; default: throw new InvalidOperationException("Can not parse: " + arg.Value); } } CLAPI.Run( Root.Instance, Kernel, Root.ActiveBuffer.Buffer, Root.Dimensions, GenMaxSize, Root.ActiveChannelBuffer, 4 ); }
public void Argument_defaults_arity_to_One_for_non_IEnumerable_types() { var argument = new Argument <int>(s => ArgumentResult.Success(1)); argument.Arity.Should().BeEquivalentTo(ArgumentArity.ExactlyOne); }
public static object GetValueOrDefault(this ArgumentResult argumentResult) => argumentResult.GetValueOrDefault <object>();
public static T GetValueOrDefault <T>(this ArgumentResult argumentResult) => argumentResult .ArgumentConversionResult .ConvertIfNeeded(argumentResult, typeof(T)) .GetValueOrDefault <T>();
private static ArcFileFormat ParseFileFormat(ArgumentResult result) { if (result.Tokens.Count == 0) { return(default);
protected virtual void VisitArgumentResult(ArgumentResult argumentResult) { }
public static void Main(string[] args) { // Make sure log file would be generated during the run GlobalSettings.GlobalLogPath = Log.StartTraceListners(); // Make sure any unhandled exceptions were logged. AppDomain.CurrentDomain.UnhandledException += (sender, e) => { try { Log.Error("Unhandled exception logged. IsTerminating: {0}.", e.IsTerminating); ExceptionHelper.CentralProcess(e.ExceptionObject as Exception); } catch (Exception ex) { Log.Error("Exception caught when trying to cast ExceptionObject to Exception."); ExceptionHelper.CentralProcess(ex); } }; Log.Info("Started with parameters:\r\n{0}".FormatWith(string.Join(" ", args))); if (args != null && args.Length > 0) { #region Console version try { RulePerfConsoleArgument consoleArgs = new RulePerfConsoleArgument(); ArgumentResult ar = RulePerfArgumentParser.ParseArgument(args, consoleArgs); if (!ar.ParseSucceeded) { Log.Info("Arguments '{0}' were not parsed successfully.".FormatWith(args != null ? string.Join(" ", args) : string.Empty)); Console.WriteLine(); ar.PrintUsage(); Environment.Exit(1); } // TODO: use StepsProcessor to handle this, so that the Step StepProcessorStep can be deleted. foreach (Step step in consoleArgs.Steps) { step.Execute(); Log.Info("Finished step <{0}> '{1}': '{2}'.".FormatWith(ar.SelectedOptionName, step.Name, step.Description)); if (step.Status != StepStatusEnum.Pass) { // Any error occurred, just stop process steps and exit with error code 1 Environment.Exit(1); } } Environment.Exit(0); } catch (Exception ex) { ExceptionHelper.CentralProcess(ex); Environment.Exit(2); } #endregion Console version } else { Log.Info("Starting with UI..."); #region GUI version Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new RulePerfForm()); #endregion GUI version } }
// parser for integer > 0 private static int ParseIntGTZero(ArgumentResult result) { return(ParseInt(result, 1)); }
// parse boolean command line arg private static bool ParseBool(ArgumentResult result) { string name = result.Parent?.Symbol.Name.ToUpperInvariant().Replace('-', '_'); if (string.IsNullOrWhiteSpace(name)) { result.ErrorMessage = "result.Parent is null"; return(false); } string errorMessage = $"--{result.Parent.Symbol.Name} must be true or false"; bool val; // bool options default to true if value not specified (ie -r and -r true) if (result.Parent.Parent.Children.FirstOrDefault(c => c.Symbol.Name == result.Parent.Symbol.Name) is OptionResult res && !res.IsImplicit && result.Tokens.Count == 0) { return(true); } // nothing to validate if (result.Tokens.Count == 0) { string env = Environment.GetEnvironmentVariable(name); if (!string.IsNullOrWhiteSpace(env)) { if (bool.TryParse(env, out val)) { return(val); } else { result.ErrorMessage = errorMessage; return(false); } } // default to true if (result.Parent.Symbol.Name == "verbose-errors") { return(true); } if (result.Parent.Symbol.Name == "verbose" && result.Parent.Parent.Children.FirstOrDefault(c => c.Symbol.Name == "run-loop") is OptionResult resRunLoop && !resRunLoop.GetValueOrDefault <bool>()) { return(true); } return(false); } if (!bool.TryParse(result.Tokens[0].Value, out val)) { result.ErrorMessage = errorMessage; return(false); } return(val); }
// parser for integer >= 0 public static int ParseIntGEZero(ArgumentResult result) { return(ParseInt(result, 0)); }
/// <summary> /// Parses the argument internal. /// </summary> /// <param name="args">The args.</param> /// <param name="argumentObject">The argument object.</param> /// <returns>Argument parsing result</returns> /// <exception cref="System.ArgumentException">IArgumentObject.Options cannot be null or empty</exception> internal static ArgumentResult ParseArgumentInternal(string[] args, RulePerfConsoleArgument argumentObject) { // Validate IArgumentObject.Options var options = argumentObject.Options; if (options == null || options.Count == 0) { throw new ArgumentException("IArgumentObject.Options cannot be null or empty"); } if (options.Select(a => a.Key.ToLower()).Distinct().Count() != options.Count) { throw new ArgumentException("IArgumentObject.Options has duplicated option name"); } // Retrieve the attributes from object's properties var optionParameterAttribDic = BuildArguParamAttrDic(options.Keys); // Parse system commandline, after this line, no exception is thrown to caller. ArgumentResult ar = new ArgumentResult(); ar.ParamAttributes = optionParameterAttribDic; ar.OptionDescriptions = options; List <KeyValuePair <string, string> > argPairs = null; try { string optionName = ParseArgumentArray(args, out argPairs); if (!optionParameterAttribDic.ContainsKey(optionName)) { throw new ArgumentException("optionName: '" + optionName + "' is not defined in argument object"); } ar.SelectedOptionName = optionName; ////#region Settings for an option argumentObject.BuildStep(ar.SelectedOptionName); CommonStep commonStep = new CommonStep(); foreach (Step step in argumentObject.Steps) { // Specific step's settings string[] settingNames = step.SettingNames.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); List <SettingEntityModel> settings = SettingEntityModel.Get(settingNames); foreach (SettingEntityModel setting in settings) { ArgumentParameterAttribute attr = new ArgumentParameterAttribute(argumentObject.GetOptionName(step)); attr.DefaultValue = setting.SettingValue; attr.Delimiter = '|'; attr.Description = setting.SettingName; attr.MaxOccur = 1; attr.MinOccur = 0; attr.ParameterName = setting.SettingName; foreach (string option in attr.OptionsBindTo) { if (optionParameterAttribDic[option].ContainsKey(attr.ParameterName)) { throw new ArgumentException(string.Format("option:{0} has multiple setting of parameter:{1}", option, attr.ParameterName)); } optionParameterAttribDic[option].Add(attr.ParameterName, attr); } } // Common settings settingNames = commonStep.SettingNames.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); settings = SettingEntityModel.Get(settingNames); foreach (SettingEntityModel setting in settings) { ArgumentParameterAttribute attr = new ArgumentParameterAttribute(argumentObject.GetOptionName(step)); attr.DefaultValue = setting.SettingValue; attr.Delimiter = '|'; attr.Description = setting.SettingName; attr.MaxOccur = 1; attr.MinOccur = 0; attr.ParameterName = setting.SettingName; foreach (string option in attr.OptionsBindTo) { if (optionParameterAttribDic[option].ContainsKey(attr.ParameterName)) { // If the setting has been set by the specifical step, then ignore the global setting process // throw new ArgumentException(string.Format("option:{0} has multiple setting of parameter:{1}", // option, attr.ParameterName)); } else { optionParameterAttribDic[option].Add(attr.ParameterName, attr); } } } } /* * foreach (var property in argumentObject.GetType().GetProperties()) * { * var paramAttrs = property.GetCustomAttributes<ArgumentParameterAttribute>(); * if (paramAttrs.Length > 0) // Only validate property with ParameterOptionAttribute * { * if (!property.PropertyType.IsSupported()) * { * throw new ArgumentException(string.Format("Property:{0}, the Type:{1} is not supported", * property.Name, * property.PropertyType.Name)); * } * * foreach (var attr in paramAttrs) * { * ValidateParameterOptionAttr(property, attr, options); * * foreach (string option in attr.OptionsBindTo) * { * if (optionParameterAttribDic[option].ContainsKey(attr.ParameterName)) * { * throw new ArgumentException(string.Format("option:{0} has multiple setting of parameter:{1}", * option, attr.ParameterName)); * } * optionParameterAttribDic[option].Add(attr.ParameterName, attr); * } * } * } * }*/ ////#endregion Settings for an option AssignValuesToArgumentObject(argumentObject, ar.SelectedOptionName, argPairs, optionParameterAttribDic[ar.SelectedOptionName]); } catch (ArgumentException ae) { ExceptionHelper.CentralProcess(ae); ar.ErrorMessages.Add(ae.Message); ar.ParseSucceeded = false; return(ar); } ar.ParseSucceeded = true; return(ar); }
private string ValidateParts(ArgumentResult result) //FileInfo file, int size) { //if (file.Length != size) // throw new ArgumentException("File size is smaller than requested."); return(null); }