public Parser Create( EnvironmentInit environmentInit = null, NewFile newFile = null, PluginInstall pluginInstall = null, PluginUninstall pluginUninstall = null, PluginList pluginList = null, SetUsername setEnvironmentSetting = null, TemplateInstall templateInstall = null, TemplateUninstall templateUninstall = null) { // if environmentInit hasn't been provided (for testing) then assign the Command Handler environmentInit ??= EnvironmentInitHandler.ExecuteAsync; newFile ??= NewFileHandler.ExecuteAsync; pluginInstall ??= PluginInstallHandler.ExecuteAsync; pluginUninstall ??= PluginUninstallHandler.ExecuteAsync; pluginList ??= PluginListHandler.ExecuteAsync; setEnvironmentSetting ??= SetEnvironmentSettingHandler.ExecuteAsync; templateInstall ??= TemplatePackageInstallerHandler.ExecuteAsync; templateUninstall ??= TemplatePackageUninstallerHandler.ExecuteAsync; // Set up intrinsic commands that will always be available. RootCommand rootCommand = Root(); rootCommand.AddCommand(Environment()); rootCommand.AddCommand(NewFile()); rootCommand.AddCommand(Plugins()); rootCommand.AddCommand(Templates()); var commandBuilder = new CommandLineBuilder(rootCommand); try { foreach (Command command in this.commandPluginHost.Discover(this.appEnvironment.PluginPaths)) { commandBuilder.AddCommand(command); } } catch (DirectoryNotFoundException) { // If this is the first run, initialize the environment and default plugins Console.WriteLine("Error Detected: vellum environment uninitialized."); Parser parser = commandBuilder.UseDefaults().Build(); int result = parser.Invoke("environment init"); if (result == ReturnCodes.Ok) { // Now the environment has been re-initialized, try to discover the plugins again. foreach (Command command in this.commandPluginHost.Discover(this.appEnvironment.PluginPaths)) { commandBuilder.AddCommand(command); } } } return(commandBuilder.UseDefaults().Build());
public static CommandLineBuilder Configure(this CommandLineBuilder builder, DependencyInjectionContainer container) { var option = new Option <Dictionary <string, object> >( "--variables", parseArgument: argResult => argResult .Tokens .Select(t => t.Value.Split('=')) .ToDictionary(p => p[0], p => { if (int.TryParse(p[1], out var n)) { return(n); } return((object)p[1]); })); var deployCommand = new Command("deploy") { option, new Option <Device>("--device", argResult => { var fromString = Device.FromString(argResult.Tokens.First().Value); return(fromString); }), new Option <bool>(new[] { "-d", "--auto-detect" }, "Use device auto-detection") }; deployCommand.Handler = CommandHandler.Create(async(bool autoDetect, Device device, IDictionary <string, object> variables) => { container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(variables)).As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); await deployer.Deploy(device, autoDetect); }); builder.AddCommand(deployCommand); var listCommand = new Command("list") { new Argument <ListType>("listType") }; listCommand.Handler = CommandHandler.Create((ListType listType) => { container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(new Dictionary <string, object>())).As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); deployer.ListFunctions(); }); builder.AddCommand(listCommand); return(builder); }
public static CommandLineBuilder Configure(this CommandLineBuilder builder, ILocatorService container) { var project = new Option <string>("--project", GetDefaultProject); var authType = new Option <AuthType>("--auth-type", "Authentication") { Required = true }; var auth = new Option <string>("--auth", "Authentication string"); var profile = new Argument <string>("profile"); var verbose = new Option <bool>("--verbose", () => false); var configureCommand = new Command("configure") { profile, project, authType, auth, verbose }; configureCommand.Handler = CommandHandler.Create <ProfileCreationOptions>(options => { var creator = container.Locate <ProfileCreationUnit>(options); return(creator.Create()); }); var deployCommand = new Command("deploy") { profile, project, authType, auth, new Option <string>("--configuration", () => "Debug", "Build configuration"), verbose }; deployCommand.Handler = CommandHandler.Create <DeploymentOptions>(async options => { var deploymentRequest = container.Locate <DeploymentUnit>(options); var deploy = await deploymentRequest.Deploy(); if (deploy.IsFailure) { Log.Error($"Deployment failed {deploy.Error}"); } }); builder.AddCommand(configureCommand); builder.AddCommand(deployCommand); return(builder); }
private static void ConfigureDeploy(CommandLineBuilder builder, DependencyInjectionContainer container) { var option = CreateVariablesOption(); var deployCommand = new Command("deploy") { option, new Option <Device>("--device", argResult => { var fromString = Device.FromString(argResult.Tokens.First().Value); return(fromString); }), new Option <bool>(new[] { "-d", "--auto-detect" }, "Use device auto-detection") }; deployCommand.Handler = CommandHandler.Create( async(bool autoDetect, Device device, IDictionary <string, object> variables) => { container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(variables)).As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); await deployer.Deploy(device, autoDetect); }); builder.AddCommand(deployCommand); }
public static CommandLineBuilder AddCommands <TCommands>(this CommandLineBuilder builder) where TCommands : class { typeof(TCommands) .GetMethodsOnly() .Select(mi => mi.CreateCommand()) .ToList() .ForEach(c => builder.AddCommand(c)); return(builder); }
public CommandInput AddCommand(Command command) { if (_cmdBuilder != null) { _cmdBuilder.AddCommand(command); } return(this); }
public static async Task <int> RunConsoleAsync(this IHost host, string[] args) { CommandLineBuilder cli = host.Services.GetRequiredService <CommandLineBuilder>(); foreach (Command cmd in host.Services.GetServices <Command>()) { cli.AddCommand(cmd); } return(await cli.UseDefaults().Build().InvokeAsync(args)); }
private static Parser BuildParser(ServiceProvider serviceProvider) { var commandLineBuilder = new CommandLineBuilder(); foreach (Command command in serviceProvider.GetServices <Command>()) { commandLineBuilder.AddCommand(command); } return(commandLineBuilder.UseDefaults().Build()); }
private static Parser BuildParser(IServiceProvider serviceProvider) { CommandLineBuilder commandLineBuilder = new CommandLineBuilder(); IEnumerable <Command> commands = serviceProvider.GetServices <Command>(); foreach (Command command in commands) { commandLineBuilder.AddCommand(command); } return(commandLineBuilder.UseDefaults().Build()); }
private Parser BuildParser(IEnumerable <Command> commands) { _logger.LogTrace("Preparing command-line parser."); var commandLineBuilder = new CommandLineBuilder(); foreach (Command command in commands) { commandLineBuilder.AddCommand(command); _logger.LogTrace("Registered command {Command}.", command.Name); } return(commandLineBuilder.UseDefaults().Build()); }
public RootCommand Build() { var builder = new CommandLineBuilder( new RootCommand( "Simple communication system between local files and a given metabase server") ) .AddOption(ArgumentBuilder.SetServerOption(SessionCredentials)) .AddOption(ArgumentBuilder.SetUserNameOption(SessionCredentials)) .AddOption(ArgumentBuilder.SetPasswordOption(SessionCredentials)) .AddOption(ArgumentBuilder.SetVerbosityOption(LoggingLevelSwitch)); CommandBuilders.ToList().ForEach(b => builder.AddCommand(b.Build())); return((RootCommand)builder.Command); }
public static async Task <int> Main(string[] args) { var loaders = new List <PluginLoader>(); var dirs = new List <IRelativeDirectoryPath> { @".\FooPlugin\bin\Debug\netcoreapp3.1\".ToRelativeDirectoryPath(), @".\BarPlugin\bin\Debug\netcoreapp3.1\".ToRelativeDirectoryPath() }; var commonDir = AppContext.BaseDirectory.ToAbsoluteDirectoryPath().ParentDirectoryPath .ParentDirectoryPath .ParentDirectoryPath .ParentDirectoryPath; foreach (var dir in dirs) { foreach (var child in dir.GetAbsolutePathFrom(commonDir).ChildrenFilesPath.Where(x => x.FileExtension == ".dll")) { var loader = PluginLoader.CreateFromAssemblyFile(child.FileInfo.FullName, sharedTypes: new[] { typeof(IPluginCommand) }); loaders.Add(loader); } } var cmd = new CommandLineBuilder(); foreach (var loader in loaders) { foreach (var pluginType in loader .LoadDefaultAssembly() .GetTypes() .Where(t => typeof(IPluginCommand).IsAssignableFrom(t) && !t.IsAbstract)) { // This assumes the implementation of IPlugin has a parameterless constructor var plugin = Activator.CreateInstance(pluginType) as IPluginCommand; cmd.AddCommand(plugin?.Command()); } } var parser = cmd.UseDefaults().Build(); return(await parser.InvokeAsync(args).ConfigureAwait(false)); }
private static void ConfigureList(CommandLineBuilder builder, DependencyInjectionContainer container) { var listCommand = new Command("list") { new Argument <ListType>("listType") }; listCommand.Handler = CommandHandler.Create((ListType listType) => { container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(new Dictionary <string, object>())) .As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); deployer.ListFunctions(); }); builder.AddCommand(listCommand); }
/// <summary> /// Displays the help for a command /// </summary> /// <param name="commandName">name of the command or alias</param> /// <param name="services">service provider</param> /// <returns>true if success, false if command not found</returns> public bool DisplayHelp(string commandName, IServiceProvider services) { Command command = null; if (!string.IsNullOrEmpty(commandName)) { command = _rootBuilder.Command.Children.OfType <Command>().FirstOrDefault((cmd) => commandName == cmd.Name || cmd.Aliases.Any((alias) => commandName == alias)); if (command == null) { return(false); } if (command.Handler is CommandHandler handler) { ITarget target = services.GetService <ITarget>(); if (!handler.IsValidPlatform(target)) { return(false); } } } else { ITarget target = services.GetService <ITarget>(); // Create temporary builder adding only the commands that are valid for the target var builder = new CommandLineBuilder(new Command(_rootBuilder.Command.Name)); foreach (Command cmd in _rootBuilder.Command.Children.OfType <Command>()) { if (cmd.Handler is CommandHandler handler) { if (handler.IsValidPlatform(target)) { builder.AddCommand(cmd); } } } command = builder.Command; } Debug.Assert(command != null); IHelpBuilder helpBuilder = new LocalHelpBuilder(this, new LocalConsole(services), useHelpBuilder: true); helpBuilder.Write(command); return(true); }
private static Parser BuildParser(IServiceProvider serviceProvider) { var rootCommand = new RootCommand(); rootCommand.Description = $"Simplify nuget package administration."; rootCommand.AddGlobalOption(CommonOptions.SilentOption); var commandLineBuilder = new CommandLineBuilder(rootCommand); var commands = serviceProvider.GetServices <Command>(); foreach (var command in commands) { commandLineBuilder.AddCommand(command); } return(commandLineBuilder .UseDefaults() .Build()); }
private static void ConfigureRunScript(CommandLineBuilder builder, DependencyInjectionContainer container) { var dictionaryOption = CreateVariablesOption(); var command = new Command("run") { new Argument <string>("scriptFile"), dictionaryOption, }; command.Handler = CommandHandler.Create( async(string scriptFile, IDictionary <string, object> variables) => { variables = variables ?? new Dictionary <string, object>(); container.Configure(x => x.ExportInstance(new DictionaryBasedSatisfier(variables)).As <IRequirementSatisfier>()); var deployer = container.Locate <WoaDeployerConsole>(); await deployer.RunScript(scriptFile); }); builder.AddCommand(command); }
private void BuildCommands(CommandLineBuilder rootBuilder, IEnumerable <Assembly> assemblies) { foreach (Type type in assemblies.SelectMany((assembly) => assembly.GetExportedTypes())) { Command command = null; var baseAttributes = (BaseAttribute[])type.GetCustomAttributes(typeof(BaseAttribute), inherit: false); foreach (BaseAttribute baseAttribute in baseAttributes) { if (baseAttribute is CommandAttribute commandAttribute) { command = new Command(commandAttribute.Name, commandAttribute.Help); var properties = new List <(PropertyInfo, Option)>(); PropertyInfo argument = null; foreach (PropertyInfo property in type.GetProperties().Where(p => p.CanWrite)) { var argumentAttribute = (ArgumentAttribute)property.GetCustomAttributes(typeof(ArgumentAttribute), inherit: false).SingleOrDefault(); if (argumentAttribute != null) { if (argument != null) { throw new ArgumentException($"More than one ArgumentAttribute in command class: {type.Name}"); } IArgumentArity arity = property.PropertyType.IsArray ? ArgumentArity.ZeroOrMore : ArgumentArity.ZeroOrOne; command.Argument = new Argument { Name = argumentAttribute.Name ?? property.Name.ToLowerInvariant(), Description = argumentAttribute.Help, ArgumentType = property.PropertyType, Arity = arity }; argument = property; } else { var optionAttribute = (OptionAttribute)property.GetCustomAttributes(typeof(OptionAttribute), inherit: false).SingleOrDefault(); if (optionAttribute != null) { var option = new Option(optionAttribute.Name ?? BuildAlias(property.Name), optionAttribute.Help, new Argument { ArgumentType = property.PropertyType }); command.AddOption(option); properties.Add((property, option)); foreach (var optionAliasAttribute in (OptionAliasAttribute[])property.GetCustomAttributes(typeof(OptionAliasAttribute), inherit: false)) { option.AddAlias(optionAliasAttribute.Name); } } else { // If not an option, add as just a settable properties properties.Add((property, null)); } } } var handler = new Handler(this, commandAttribute.AliasExpansion, argument, properties, type); _commandHandlers.Add(command.Name, handler); command.Handler = handler; rootBuilder.AddCommand(command); } if (baseAttribute is CommandAliasAttribute commandAliasAttribute) { if (command == null) { throw new ArgumentException($"No previous CommandAttribute for this CommandAliasAttribute: {type.Name}"); } command.AddAlias(commandAliasAttribute.Name); } } } }
private void BuildCommands(CommandLineBuilder rootBuilder, IEnumerable <Assembly> assemblies) { foreach (Type type in assemblies.SelectMany((assembly) => assembly.GetExportedTypes())) { Command command = null; var commandAttributes = (CommandAttribute[])type.GetCustomAttributes(typeof(CommandAttribute), inherit: false); foreach (CommandAttribute commandAttribute in commandAttributes) { // If there is a previous command and the current command doesn't have help or alias expansion, use "simple" aliasing if (command != null && commandAttribute.Help == null && commandAttribute.AliasExpansion == null) { command.AddAlias(commandAttribute.Name); continue; } command = new Command(commandAttribute.Name, commandAttribute.Help); var builder = new CommandLineBuilder(command); builder.UseHelp(); var properties = new List <(PropertyInfo, Option)>(); PropertyInfo argument = null; foreach (PropertyInfo property in type.GetProperties().Where(p => p.CanWrite)) { var argumentAttribute = (ArgumentAttribute)property.GetCustomAttributes(typeof(ArgumentAttribute), inherit: false).SingleOrDefault(); if (argumentAttribute != null) { if (argument != null) { throw new ArgumentException($"More than one ArgumentAttribute in command class: {type.Name}"); } command.Argument = new Argument { Name = argumentAttribute.Name ?? property.Name.ToLowerInvariant(), Description = argumentAttribute.Help, ArgumentType = property.PropertyType, Arity = new ArgumentArity(0, int.MaxValue) }; argument = property; } else { var optionAttribute = (OptionAttribute)property.GetCustomAttributes(typeof(OptionAttribute), inherit: false).SingleOrDefault(); if (optionAttribute != null) { var option = new Option(optionAttribute.Name ?? BuildAlias(property.Name), optionAttribute.Help, new Argument { ArgumentType = property.PropertyType }); command.AddOption(option); properties.Add((property, option)); foreach (var optionAliasAttribute in (OptionAliasAttribute[])property.GetCustomAttributes(typeof(OptionAliasAttribute), inherit: false)) { option.AddAlias(optionAliasAttribute.Name); } } else { // If not an option, add as just a settable properties properties.Add((property, null)); } } } command.Handler = new Handler(this, commandAttribute.AliasExpansion, argument, properties, type); rootBuilder.AddCommand(command); } } }