private static void AppendVerbHelpText(StringBuilder sb, VerbAttribute attrib, char argPrefix, PropertyInfo[] verbProperties) { string cmd = attrib.Name; if (verbProperties.Length > 0) { cmd += " [options]"; } sb.AppendFormat(" {0,-25}{1}", cmd, attrib.Description); sb.AppendLine(); foreach (PropertyInfo param in verbProperties) { var paramAttrib = param.GetCustomAttributes(typeof(NamedArgumentExAttribute), false) .FirstOrDefault() as NamedArgumentExAttribute; if (paramAttrib != null) { AppendArgHelpText(sb, argPrefix, paramAttrib); } } sb.AppendLine(); }
private static List <string> Create(VerbAttribute verb) { return(new List <string>() { verb.Name }); }
public void IsNameSetCorrectly() { const string name = "name"; var verb = new VerbAttribute(name); Assert.AreEqual(name, verb.Name); }
public static Verb FromAttribute(VerbAttribute attribute) { return new Verb( attribute.Name, attribute.HelpText ); }
public static Verb FromAttribute(VerbAttribute attribute) { return(new Verb( attribute.Name, attribute.HelpText )); }
private static Command CreateCommand(Type type, VerbAttribute verbAttribute) { ImmutableArray <CommandArgument> .Builder arguments = ImmutableArray.CreateBuilder <CommandArgument>(); ImmutableArray <CommandOption> .Builder options = ImmutableArray.CreateBuilder <CommandOption>(); Dictionary <string, string> providerMap = type .GetCustomAttributes <OptionValueProviderAttribute>() .ToDictionary(f => f.PropertyName, f => f.ProviderName); foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { OptionAttribute optionAttribute = null; foreach (Attribute attribute in propertyInfo.GetCustomAttributes()) { if (attribute is ValueAttribute valueAttribute) { var argument = new CommandArgument( index: valueAttribute.Index, name: valueAttribute.MetaName, description: valueAttribute.HelpText, isRequired: valueAttribute.Required); arguments.Add(argument); break; } else if (optionAttribute == null) { optionAttribute = attribute as OptionAttribute; if (optionAttribute != null) { continue; } } } if (optionAttribute != null) { Debug.Assert(propertyInfo.PropertyType != typeof(bool) || string.IsNullOrEmpty(optionAttribute.MetaValue), $"{type.Name}.{propertyInfo.Name}"); var option = new CommandOption( name: optionAttribute.LongName, shortName: optionAttribute.ShortName, metaValue: optionAttribute.MetaValue, description: optionAttribute.HelpText, isRequired: optionAttribute.Required, valueProviderName: (providerMap.TryGetValue(propertyInfo.Name, out string valueProviderName)) ? valueProviderName : null); options.Add(option); } } return(new Command( verbAttribute.Name, verbAttribute.HelpText, arguments.OrderBy(f => f.Index), options.OrderBy(f => f.Name, StringComparer.InvariantCulture))); }
private Verb GetVerbFrom(IVerbOptions parsed) { VerbAttribute verbAttribute = parsed.GetType().GetCustomAttribute <VerbAttribute>(); string verbName = verbAttribute.Name; Verb verb = VerbHelper.FromName(verbName); return(verb); }
public static Verb FromAttribute(VerbAttribute attribute) { return(new Verb( attribute.Name, attribute.HelpText, attribute.Alias, attribute.Hidden )); }
/// <summary> /// Creates a <see cref="Verb"/> from a <see cref="VerbAttribute"/>. /// </summary> /// <param name="attribute">The attribute to create the verb from.</param> /// <exception cref="ArgumentNullException"></exception> /// <returns>The created <see cref="Verb"/> instance.</returns> public static Verb FromAttribute(VerbAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } return(new Verb(attribute.Name, attribute.HelpText)); }
public void IsHelpTextSetCorrectly() { const string helpText = "SomeHelp"; var verb = new VerbAttribute("name") { HelpText = helpText }; Assert.AreEqual(helpText, verb.HelpText); }
private void TestHelpWrittenForVerbs(StringBuilder helpBuilder, params Type[] verbsInHelp) { string[] helpLines = helpBuilder.ToString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); int helpIndex = 4; foreach (Type verbType in verbsInHelp) { VerbAttribute verbAttribute = (VerbAttribute)verbType.GetCustomAttributes(typeof(VerbAttribute), false)[0]; NormalizeHelpLine(helpLines[helpIndex]).Should().Be(NormalizeHelpLine($"{verbAttribute.Name}{verbAttribute.HelpText}")); helpIndex++; } }
public static IEnumerable <Command> LoadCommands(Assembly assembly) { foreach (System.Reflection.TypeInfo type in assembly.GetTypes()) { if (!type.IsAbstract) { VerbAttribute verbAttribute = type.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { yield return(CreateCommand(type, verbAttribute)); } } } }
private void AppendVerbHelpText(StringBuilder sb, VerbAttribute attrib, char argPrefix, PropertyInfo[] verbProperties) { var namedArgAttributes = new List <NamedArgumentAttribute>(); var cmd = new StringBuilder(attrib.Name); foreach (PropertyInfo param in verbProperties) { var positionalArg = GetAttribute <PositionalArgumentAttribute>(param); var namedArg = GetAttribute <NamedArgumentAttribute>(param); if (positionalArg?.MetaVar != null) { cmd.AppendFormat(" <{0}>", positionalArg.MetaVar); } if (namedArg != null) { namedArgAttributes.Add(namedArg); } } if (namedArgAttributes.Count > 0) { cmd.Append(" [options]"); } sb.Append(" "); sb.AppendFormat($"{{0,{-DescriptionDistance}}}", cmd.ToString()); if (cmd.Length >= DescriptionDistance) { sb.AppendLine(); sb.Append(" "); sb.AppendFormat($"{{0,{-DescriptionDistance}}}", ""); } sb.Append(attrib.Description); sb.AppendLine(); foreach (NamedArgumentAttribute arg in namedArgAttributes) { AppendArgHelpText(sb, argPrefix, arg); } sb.AppendLine(); }
private void AppendVerbHelpText(StringBuilder sb, VerbAttribute attrib, char argPrefix, PropertyInfo[] verbProperties) { string cmd = attrib.Name; foreach (PropertyInfo param in verbProperties) { var paramAttrib = GetAttribute <PositionalArgumentAttribute>(param); if (paramAttrib?.MetaVar != null) { cmd += $" <{paramAttrib.MetaVar}>"; } } if (verbProperties.Length > 0) { cmd += " [options]"; } sb.Append(" "); sb.AppendFormat($"{{0,{-DescriptionDistance}}}", cmd); if (cmd.Length >= DescriptionDistance) { sb.AppendLine(); sb.Append(" "); sb.AppendFormat($"{{0,{-DescriptionDistance}}}", ""); } sb.Append(attrib.Description); sb.AppendLine(); foreach (PropertyInfo param in verbProperties) { var paramAttrib = GetAttribute <NamedArgumentAttribute>(param); if (paramAttrib != null) { AppendArgHelpText(sb, argPrefix, paramAttrib); } } sb.AppendLine(); }
public static Command LoadCommand(Assembly assembly, string commandName) { foreach (System.Reflection.TypeInfo type in assembly.GetTypes()) { if (type.IsAbstract) { continue; } VerbAttribute verbAttribute = type.GetCustomAttribute <VerbAttribute>(); if (verbAttribute?.Name == commandName) { return(CreateCommand(type, verbAttribute)); } } return(null); }
internal VerbNode(Type verb) { Type = verb; Attr = VerbAttribute.FromType(verb); OptionNodes = new List <OptionNode>(); // Add member option fields foreach (FieldInfo info in verb.GetFields()) { if (info.GetCustomAttributes(true).Any(attr => attr is OptionAttribute)) { OptionNodes.Add(new FieldOptionNode(info)); } } // Add member option properties foreach (PropertyInfo info in verb.GetProperties()) { if (info.GetCustomAttributes(true).Any(attr => attr is OptionAttribute)) { OptionNodes.Add(new PropertyOptionNode(info)); } } }
private static int Main(string[] args) { //WriteLine($"Orang Command Line Tool version {typeof(Program).GetTypeInfo().Assembly.GetName().Version}"); //WriteLine("Copyright (c) Josef Pihrt. All rights reserved."); //WriteLine(); if (args != null) { if (args.Length == 1) { if (IsHelpOption(args[0])) { Console.Write(HelpProvider.GetHelpText()); return(0); } } else if (args.Length == 2) { if (args?.Length == 2 && IsHelpOption(args[1])) { Command command = CommandLoader.LoadCommand(typeof(HelpCommand).Assembly, args[0]); if (command != null) { Console.Write(HelpProvider.GetHelpText(command)); return(0); } } } } try { ParserSettings defaultSettings = Parser.Default.Settings; var parser = new Parser(settings => { settings.AutoHelp = false; settings.AutoVersion = defaultSettings.AutoVersion; settings.CaseInsensitiveEnumValues = defaultSettings.CaseInsensitiveEnumValues; settings.CaseSensitive = defaultSettings.CaseSensitive; settings.EnableDashDash = true; settings.HelpWriter = null; settings.IgnoreUnknownArguments = defaultSettings.IgnoreUnknownArguments; settings.MaximumDisplayWidth = defaultSettings.MaximumDisplayWidth; settings.ParsingCulture = defaultSettings.ParsingCulture; }); ParserResult <object> parserResult = parser.ParseArguments < CopyCommandLineOptions, DeleteCommandLineOptions, EscapeCommandLineOptions, FindCommandLineOptions, HelpCommandLineOptions, ListSyntaxCommandLineOptions, MatchCommandLineOptions, MoveCommandLineOptions, RenameCommandLineOptions, ReplaceCommandLineOptions, SplitCommandLineOptions >(args); bool help = false; bool success = true; parserResult.WithNotParsed(_ => { var helpText = new HelpText(SentenceBuilder.Create(), HelpProvider.GetHeadingText()); helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); VerbAttribute verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { helpText.AddPreOptionsText(Environment.NewLine + HelpProvider.GetFooterText(verbAttribute.Name)); } Console.Error.WriteLine(helpText); success = false; }); parserResult.WithParsed <AbstractCommandLineOptions>(options => { if (options.Help) { string commandName = options.GetType().GetCustomAttribute <VerbAttribute>().Name; Console.WriteLine(HelpProvider.GetHelpText(commandName)); help = true; return; } success = false; var defaultVerbosity = Verbosity.Normal; if (options.Verbosity == null || TryParseVerbosity(options.Verbosity, out defaultVerbosity)) { ConsoleOut.Verbosity = defaultVerbosity; if (TryParseOutputOptions(options.Output, OptionNames.Output, out string filePath, out Verbosity fileVerbosity, out Encoding encoding, out bool append)) { if (filePath != null) { FileMode fileMode = (append) ? FileMode.Append : FileMode.Create; var stream = new FileStream(filePath, fileMode, FileAccess.Write, FileShare.Read); var writer = new StreamWriter(stream, encoding, bufferSize: 4096, leaveOpen: false); Out = new TextWriterWithVerbosity(writer) { Verbosity = fileVerbosity }; } success = true; } else { success = false; } } }); if (help) { return(0); } if (!success) { return(2); } return(parserResult.MapResult( (CopyCommandLineOptions options) => Copy(options), (MoveCommandLineOptions options) => Move(options), (DeleteCommandLineOptions options) => Delete(options), (EscapeCommandLineOptions options) => Escape(options), (FindCommandLineOptions options) => Find(options), (HelpCommandLineOptions options) => Help(options), (ListSyntaxCommandLineOptions options) => ListSyntax(options), (MatchCommandLineOptions options) => Match(options), (RenameCommandLineOptions options) => Rename(options), (ReplaceCommandLineOptions options) => Replace(options), (SplitCommandLineOptions options) => Split(options), _ => 2)); }
private static OptionKind GetValueKind22(OptionAttribute option, ValueAttribute value, VerbAttribute verb) { if (verb != null) { return(OptionKind.Verb); } if (option != null) { return(option.Separator == '\0' ? OptionKind.Single : OptionKind.List); } if (value != null) { return(OptionKind.Single); } return(OptionKind.Unknown); }
public static string GetClassVerb <T>() { VerbAttribute verbAttr = typeof(T).GetCustomAttribute <VerbAttribute>(); return(verbAttr.Name); }
private static int Main(string[] args) { #if DEBUG if (args.LastOrDefault() == "--debug") { WriteArgs(args.Take(args.Length - 1).ToArray(), Verbosity.Quiet); return(ExitCodes.NotSuccess); } #endif Parser parser = null; try { parser = CreateParser(ignoreUnknownArguments: true); if (args == null || args.Length == 0) { HelpCommand.WriteCommandsHelp(); return(ExitCodes.Success); } bool?success = null; ParserResult <BaseCommandLineOptions> defaultResult = parser .ParseArguments <BaseCommandLineOptions>(args) .WithParsed(options => { if (!options.Help) { return; } string commandName = args?.FirstOrDefault(); Command command = (commandName != null) ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName) : null; if (!ParseVerbosityAndOutput(options)) { success = false; return; } WriteArgs(args, Verbosity.Diagnostic); if (command != null) { HelpCommand.WriteCommandHelp(command); } else { HelpCommand.WriteCommandsHelp(); } success = true; }); if (success == false) { return(ExitCodes.Error); } if (success == true) { return(ExitCodes.Success); } parser = CreateParser(); ParserResult <object> parserResult = parser.ParseArguments( args, new Type[] { typeof(AnalyzeCommandLineOptions), typeof(FixCommandLineOptions), typeof(FormatCommandLineOptions), typeof(GenerateDocCommandLineOptions), typeof(GenerateDocRootCommandLineOptions), typeof(HelpCommandLineOptions), typeof(ListSymbolsCommandLineOptions), typeof(LogicalLinesOfCodeCommandLineOptions), typeof(MigrateCommandLineOptions), typeof(PhysicalLinesOfCodeCommandLineOptions), typeof(RenameSymbolCommandLineOptions), typeof(SpellcheckCommandLineOptions), #if DEBUG typeof(AnalyzeAssemblyCommandLineOptions), typeof(FindSymbolsCommandLineOptions), typeof(GenerateSourceReferencesCommandLineOptions), typeof(ListVisualStudioCommandLineOptions), typeof(ListReferencesCommandLineOptions), typeof(SlnListCommandLineOptions), #endif }); parserResult.WithNotParsed(e => { if (e.Any(f => f.Tag == ErrorType.VersionRequestedError)) { Console.WriteLine(typeof(Program).GetTypeInfo().Assembly.GetName().Version); success = false; return; } var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText()); helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText); VerbAttribute verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>(); if (verbAttribute != null) { helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name)); } Console.Error.WriteLine(helpText); success = false; }); if (success == true) { return(ExitCodes.Success); } if (success == false) { return(ExitCodes.Error); } parserResult.WithParsed <AbstractCommandLineOptions>( options => { if (ParseVerbosityAndOutput(options)) { WriteArgs(args, Verbosity.Diagnostic); } else { success = false; } }); if (success == false) { return(ExitCodes.Error); } return(parserResult.MapResult( (MSBuildCommandLineOptions options) => { switch (options) { case AnalyzeCommandLineOptions analyzeCommandLineOptions: return AnalyzeAsync(analyzeCommandLineOptions).Result; case FixCommandLineOptions fixCommandLineOptions: return FixAsync(fixCommandLineOptions).Result; case FormatCommandLineOptions formatCommandLineOptions: return FormatAsync(formatCommandLineOptions).Result; case GenerateDocCommandLineOptions generateDocCommandLineOptions: return GenerateDocAsync(generateDocCommandLineOptions).Result; case GenerateDocRootCommandLineOptions generateDocRootCommandLineOptions: return GenerateDocRootAsync(generateDocRootCommandLineOptions).Result; case ListSymbolsCommandLineOptions listSymbolsCommandLineOptions: return ListSymbolsAsync(listSymbolsCommandLineOptions).Result; case LogicalLinesOfCodeCommandLineOptions logicalLinesOfCodeCommandLineOptions: return LogicalLinesOrCodeAsync(logicalLinesOfCodeCommandLineOptions).Result; case PhysicalLinesOfCodeCommandLineOptions physicalLinesOfCodeCommandLineOptions: return PhysicalLinesOfCodeAsync(physicalLinesOfCodeCommandLineOptions).Result; case RenameSymbolCommandLineOptions renameSymbolCommandLineOptions: return RenameSymbolAsync(renameSymbolCommandLineOptions).Result; case SpellcheckCommandLineOptions spellcheckCommandLineOptions: return SpellcheckAsync(spellcheckCommandLineOptions).Result; #if DEBUG case FindSymbolsCommandLineOptions findSymbolsCommandLineOptions: return FindSymbolsAsync(findSymbolsCommandLineOptions).Result; case GenerateSourceReferencesCommandLineOptions generateSourceReferencesCommandLineOptions: return GenerateSourceReferencesAsync(generateSourceReferencesCommandLineOptions).Result; case ListReferencesCommandLineOptions listReferencesCommandLineOptions: return ListReferencesAsync(listReferencesCommandLineOptions).Result; case SlnListCommandLineOptions slnListCommandLineOptions: return SlnListAsync(slnListCommandLineOptions).Result; #endif default: throw new InvalidOperationException(); } }, (AbstractCommandLineOptions options) => { switch (options) { case HelpCommandLineOptions helpCommandLineOptions: return Help(helpCommandLineOptions); case MigrateCommandLineOptions migrateCommandLineOptions: return Migrate(migrateCommandLineOptions); #if DEBUG case AnalyzeAssemblyCommandLineOptions analyzeAssemblyCommandLineOptions: return AnalyzeAssembly(analyzeAssemblyCommandLineOptions); case ListVisualStudioCommandLineOptions listVisualStudioCommandLineOptions: return ListVisualStudio(listVisualStudioCommandLineOptions); #endif default: throw new InvalidOperationException(); } }, _ => ExitCodes.Error)); } catch (Exception ex) when(ex is AggregateException || ex is FileNotFoundException || ex is InvalidOperationException) { WriteError(ex); } finally { parser?.Dispose(); Out?.Dispose(); Out = null; } return(ExitCodes.Error); }
private static async Task <int> Main(string[] args) { VirtualTerminal.Enable(); int exitCode = 0; DevAccount account = ToolAuthentication.LoadLastSignedInUser(); if (account == null) { Console.Error.WriteLine("Didn't find dev signin info, please use \"XblDevAccount.exe signin\" to initiate."); return(-1); } if (account.AccountSource != DevAccountSource.WindowsDevCenter) { Console.Error.WriteLine("You must sign in with a valid Windows Dev Center account."); } string invokedVerb = null; object opts = null; Console.WriteLine($"Using Dev account {account.Name} from {account.AccountSource}"); try { // Find all of the subclasses which inherit from BaseOptions. Type[] argumentTypes = typeof(Program).GetNestedTypes(BindingFlags.NonPublic).Where(c => c.IsSubclassOf(typeof(BaseOptions))).ToArray(); // Only assign the option and verb here, as the commandlineParser doesn't support async callback yet. Parser.Default.ParseArguments(args, argumentTypes) .WithParsed(options => { VerbAttribute verbAttribute = Attribute.GetCustomAttribute(options.GetType(), typeof(VerbAttribute)) as VerbAttribute; invokedVerb = verbAttribute?.Name; opts = options; }) .WithNotParsed(err => exitCode = -1); if (opts != null) { // Find property called AccountId. If it not set, then set it to the logged in user's account Id. PropertyInfo accountIdProperty = opts.GetType().GetProperty("AccountId"); if (accountIdProperty != null) { Guid accountIdPropertyValue = (Guid)accountIdProperty.GetValue(opts); if (accountIdPropertyValue == Guid.Empty) { accountIdProperty.SetValue(opts, new Guid(account.AccountId)); } } // Find the method which takes this class as an argument. MethodInfo method = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.NonPublic).Where(c => c.GetParameters().FirstOrDefault()?.ParameterType == opts.GetType()).FirstOrDefault(); if (method == null) { // This should never happen, but just in case... throw new InvalidOperationException($"Method with parameter {opts.GetType()} not found."); } Task <int> methodResult = (Task <int>)method.Invoke(null, new object[] { opts }); exitCode = await methodResult; } } catch (HttpRequestException ex) { Console.Error.WriteLine($"Error: XblConfig {invokedVerb} failed."); if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Unauthorized))) { Console.Error.WriteLine( $"Unable to authorize the account with the XboxLive service, please contact your administrator."); } else if (ex.Message.Contains(Convert.ToString((int)HttpStatusCode.Forbidden))) { Console.Error.WriteLine( "Your account doesn't have access to perform the operation, please contact your administrator."); } else { Console.WriteLine(ex.Message); } exitCode = -1; } catch (Exception ex) { Console.Error.WriteLine("Error: unexpected error found."); Console.Error.WriteLine(ex.Message); exitCode = -1; } if (System.Diagnostics.Debugger.IsAttached) { Console.Read(); } return(exitCode); }