public static string Do(CommandLineInterpreterConfiguration config, string[] commands, int width)
        {
            var sb = new StringBuilder();
            var interpreter = new CommandLineInterpreter(config);
            foreach (var command in commands)
            {
                sb.AppendLine(string.Format("Test: {0}", command));
                sb.AppendLine();

                var args = CommandLineTokeniser.Tokenise(command);
                string[] errors;
                var result = interpreter.Interpret(args, out errors, false);
                if (errors != null &&errors.Any())
                {
                    foreach (var e in errors)
                    {
                        sb.AppendLine(e);
                    }
                }
                else
                {
                    DisplayType(sb, result);
                }

                sb.AppendLine();
                sb.AppendLine();
            }

            return sb.ToString();
        }
 public void Initialise(ConsoleApplicationBase app, MethodParameterInjector injector, CommandLineInterpreterConfiguration config, Dictionary<Type, ICommandHandler> handlers)
 {
     _app = app;
     _injector = injector;
     _config = config;
     _handlers = handlers;
 }
Exemplo n.º 3
0
 public static void Describe(CommandLineInterpreterConfiguration config, IConsoleAdapter console, string applicationName, CommandExecutionMode executionMode, IOptionNameHelpAdorner adorner = null)
 {
     if (config.DefaultCommand != null && executionMode == CommandExecutionMode.CommandLine)
         AddDefaultCommandText(console, config.DefaultCommand, applicationName, adorner);
     else
         AddCommandListText(console, config, adorner, executionMode);
 }
 public InteractiveSession(ConsoleApplicationBase app, MethodParameterInjector injector, Dictionary<Type, ICommandHandler> handlers, IConsoleAdapter console, IErrorAdapter error, CommandLineInterpreterConfiguration config)
 {
     _app = app;
     _injector = injector;
     _handlers = handlers;
     _console = console;
     _error = error;
     _config = config;
     _interpreter = new CommandLineInterpreter(_config);
 }
Exemplo n.º 5
0
 private static void AddCommandListText(IConsoleAdapter console, CommandLineInterpreterConfiguration config, IOptionNameHelpAdorner adorner, CommandExecutionMode executionMode)
 {
     var commands = config.Commands.Where(c => c.Name != null && CommandModeFilter(executionMode, c)).OrderBy(c => c.Name).ToList();
     if (commands.Any())
     {
         console.WriteLine("Available commands");
         console.WriteLine();
         var commandItems = commands.Select(c => new { Command = c.Name, Text = FormatShortCommandDescription(c) });
         console.FormatTable(commandItems, FormattingOptions, ColumnSeperator);
     }
 }
        public static void Describe(CommandLineInterpreterConfiguration config, ConsoleAdapter console, string applicationName, CommandLineParserConventions conventions)
        {
            CommandDescriber.Describe(config, console, applicationName, CommandExecutionMode.CommandLine);

            var adorner = MakeAdorner(conventions);
            foreach (var baseCommandConfig in config.Commands)
            {
                console.WriteLine();
                console.WriteLine("Description of {0} command:", baseCommandConfig.Name);
                CommandDescriber.Describe(baseCommandConfig, console, CommandExecutionMode.CommandLine, adorner);
            }
        }
Exemplo n.º 7
0
        protected override void Initialise()
        {
            Config = new CommandLineInterpreterConfiguration();
            Handlers = new Dictionary<Type, ICommandHandler>();

            foreach (var type in _commands)
            {
                Config.Load(type);
                foreach(var handler in CommandHandlerLoader.LoadHandlerMethods(type, _commands, Injector.Value))
                    Handlers[handler.CommandType] = handler;
            }
            base.Initialise();
        }
        public void ACustomConverterCanBeSpecifiedAndUsed()
        {
            CommandLineInterpreterConfiguration.AddCustomConverter(s => s.Length > 1 ? new CustomParamType(s.First(), s.Substring(1)) : null);
            var config = new CommandLineInterpreterConfiguration();
            config
                .Parameters(() => new CustomParamCommand())
                .Description("Description of the whole program.")
                .Positional<CustomParamType>("pos", (command, s) => { })
                    .Description("A positional parameter.");

            CommandDescriber.Describe(config, _console, _applicationName, CommandExecutionMode.CommandLine);
            var description = _consoleOutInterface.GetBuffer();
            Console.WriteLine(description);
            Approvals.Verify(description);
        }
        public void DefaultCommandHelpIsFormatted()
        {
            var config = new CommandLineInterpreterConfiguration();
            config
                .Parameters(() => new TestCommand())
                .Description("Description of the whole program.")
                .Positional<string>("pos", (command, s) => { })
                .Description("A positional parameter.");

            config.DefaultCommand.Name = "shouldnotbedisplayed";

            _console.WriteLine(RulerFormatter.MakeRuler(_console.WindowWidth));
            CommandDescriber.Describe(config, _console, "Test", CommandExecutionMode.CommandLine);
            var buffer = _consoleOutInterface.GetBuffer();
            Console.WriteLine(buffer);
            Approvals.Verify(buffer);
        }
Exemplo n.º 10
0
        private static CommandLineInterpreterConfiguration ConfigureCommandLine()
        {
            var config = new CommandLineInterpreterConfiguration(CommandLineParserConventions.MsDosConventions);
            config.Parameters<Options>("SetCsprojVer")
                .Description(@"SetCsprojVer is a simple tool to update the version number in AssemblyInfo.cs files in a project tree.

            A project folder should be supplied, and this will scanned for AssemblyInfo.cs files. Each file found will be edited to select the appropriate version number.")
                .Positional("projectfolder")
                    .Description("The base folder for the scan.")
                .Option("AV", o => o.AssemblyVersion)
                    .Description("Set the AssemblyVersion to the specified value. This must be a 4 part version number, " +
                                 "if specified. e.g. /AV:1.0.0.0")
                .Option("FV", o => o.AssemblyFileVersion)
                    .Description("Set the AssemblyFileVersion to the specified value. This must be a 4 part version number, " +
                                 "if specified. e.g. /FV:1.0.0.0")
                .Option("IV", o => o.AssemblyInformationalVersion)
                    .Description("Set the AssemblyInformationalVersion to the specified value. e.g. \"/IV:1.0 beta\"")
                .Option<string, string>("inc", (o, s, p) => o.SetIncTarget(s, p))
                    .Description("Increment a component of either the AssemblyVersion (AV) or the AssemblyFileVersion (FV). " +
                                 "The component incremented is either the build (b) or revision (r). " + Environment.NewLine +
                                 "Specify [AV|FV],[B|R], e.g. /inc:av,b")
                    .Alias("I")
                .Option("env", o => o.EnvironmentVariableName)
                    .Description("Set an environment variable to the version number set. " +
                                 "This may not be specified if more than one of the /AV, /FV, or /IV options are specified. " +
                                 "If the /inc option is specified, the environment variable will receive the result of the increment. " +
                                 "In a dry run, the environment variable will still be set. e.g. /env:variable")
                    .Alias("e")
                .Option("Report")
                    .Description("Report the version numbers defined in the AssemblyInfo.cs files found in the project tree. " +
                                 "This option may not be combined with any others.")
                    .Alias("R")
                .Option("Get")
                    .Description("Retrieve a the first version number defined in the AssemblyInfo.cs files for either the " +
                                 "AssemblyVersion (AV), the AssemblyFileVersion (FV) or the AssemblyInformationalVersion (IV). " +
                                 "This option may not be combined with options that change a version number, or the report option. " +
                                 "If the Env option is also used, the discovered version number will be placed in an environment variable. " +
                                 "e.g. /get:av")
                    .Alias("G")
                .Option("dryrun")
                    .Alias("D")
                    .Description("Perform a dry run. No updates will be made. e.g. /dryrun or /D")
                .Validator(Options.Validator);
            return config;
        }
        private void Configure(CommandLineInterpreterConfiguration config)
        {
            config.Command("c1", s => new C1Data(s))
                .Description("Command 1 a file.")
                .Positional<string>("filename", (c, s) => c.FileName = s)
                    .Description("The name of the file.")
                .Option("delete", (c, b) => c.DeleteAfter = b)
                    .Alias("D")
                    .Description("Delete the file after processing.")
                .Option<string>("archive", (c, s) => c.ArchiveLocation = s)
                    .Alias("A")
                    .Description("Archive after processing");

            config.Command<C2Data>("c2")
                .Description("Command 2 an archive")
                .Positional("name", c => c.ArchiveName)
                    .Description("The name of the archive.")
                .Positional("keep", c => c.DaysToKeep)
                    .Description("The number of days to keep the archive")
                .Option("maxSize", c => c.MaxSize)
                    .Alias("M")
                    .Description("The maximum size of the archive.");

            config.Command<C3Data>("c3")
                .Description("Generate loads of spam")
                .Positional("iterations")
                    .Description("Number of times to repeat")
                .Positional("Message")
                    .Description("The message to spam.")
                .Positional("OverrunLength")
                    .Description("Amount packet should be longer than it claims.")
                    .DefaultValue("5")
                .Option("kidding")
                    .Alias("K")
                    .Description("Run in just kidding mode.");
        }
 public void ConfiguringDefaultCommandTwiceThrows()
 {
     var config = new CommandLineInterpreterConfiguration();
     config
         .Parameters(() => "test")
         .Positional<string>("opt", (s, x) => { });
     config
         .Parameters(() => "test again")
         .Positional<int>("opt2", (s, x) => { });
 }
 public void ConfiguringTheSameCommandTwiceThrows()
 {
     var config = new CommandLineInterpreterConfiguration();
     config
         .Command("test", s => s)
         .Option<string>("opt", (s, x) => { });
     config
         .Command("test", s => s)
         .Option<string>("opt", (s, x) => { });
 }
        public void DefaultCommandHelpIsFormatted()
        {
            var config = new CommandLineInterpreterConfiguration();
            config
                .Parameters(() => new TestCommand())
                .Description("Description of the whole program.")
                .Positional<string>("pos", (command, s) => { })
                    .Description("A positional parameter.");

            CommandDescriber.Describe(config, _console, _applicationName, CommandExecutionMode.CommandLine);
            var description = _consoleOutInterface.GetBuffer();
            Console.WriteLine(description);
            Approvals.Verify(description);
        }
 public void DefaultValueIsStoredOnOptionalParameter()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Parameters(() => new MultiCaseCommand())
         .Positional("AOne").DefaultValue("X");
     Assert.That(config.DefaultCommand.Positionals[0].DefaultValue, Is.EqualTo("X"));
 }
 internal override void LoadConfigFromAssembly()
 {
     Config = new CommandLineInterpreterConfiguration();
 }
 private void Configure(CommandLineInterpreterConfiguration config)
 {
     config.Load(typeof (C1Data));
     config.Load(typeof (C2Data));
     config.Load(typeof (C3Data));
 }
 public void PositionalWithDefaultValueIsOptional()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Parameters(() => new MultiCaseCommand())
         .Positional("AOne").DefaultValue("X");
     Assert.That(config.DefaultCommand.Positionals[0].IsOptional, Is.True);
 }
        public void SetUp()
        {
            _config = new CommandLineInterpreterConfiguration();
            _config.Command("first", s => new TestCommand())
                .Description("Description of the first commmand.");
            _config
                .Command("second", s => new TestCommand())
                .Description("The second command is a command with a number of parameters.")
                .Positional<string>("dateofthing", (command, s) => { })
                    .Description("The date the thing should have.")
                .Positional<string>("numberofthing", (command, s) => { })
                    .Description("The number of things that should be.");
            _config
                .Command("third", s => new TestCommand())
                .Description("The third command has a number of options but no parameters.")
                .Option("on", (command, b) => { })
                    .Description("A simple option with no argument.")
                .Option<string, int>("fiddly", (command, s, n) => { })
                    .Alias("f")
                    .Description("An option with two arguments. The arguments need to be described in the text.");
            _config
                .Command("fourth", s => new TestCommand())
                .Description("The fourth command is really complicated with a number of parameters and also options. This is the sort of command that needs lots of text.")
                .Positional<string>("date", (command, s) => { })
                    .Description("The date the complicated nonsense should be forgotten.")
                .Positional<string>("crpyticnum", (command, s) => { })
                    .Description("The amount of nonsense the user needs to forget.")
                .Option("ignore", (command, b) => { })
                    .Description("Use this option to consign this command to history, where it belongs.")
                .Option<string, int>("more", (command, s, n) => { })
                    .Description("Even more.");

            _config
                .Command("desc", s => new TestCommand())
                .Description(
                    @"Descriptions can contain embedded line breaks -->
            <-- like that one. These should be respected in the formatting. (This is meant to look a bit odd. Also, you should be aware that the deliberate line break is the only one in this text.)")
                .Positional<string>("pos", (command, s) => { })
                    .Description(@"A parameter with
            a line break.")
                .Option("lb", (command, b) => { })
                    .Description("Another\nbreak.");

            _config
                .Command("exp", s => new TestCommand())
                .Description(@"Command with a positional and options configured using a Linq Expression, not a lambda.")
                .Positional("pos", command => command.StringProp)
                    .Description(@"A positional configured with an expression.")
                .Option("B", command => command.BoolProp)
                    .Description("A boolean option configured with an expression.")
                .Option("I", command => command.IntProp)
                    .Description("A boolean option configured with an expression.");

            _customParser = new CustomParser();

            _consoleOutInterface = new ConsoleInterfaceForTesting();
            _console = new ConsoleAdapter(_consoleOutInterface);

            _console.WriteLine(RulerFormatter.MakeRuler(40));
        }
 public void PositionalDefinedOnlyByNameMatchesPropertyAutomatically()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Parameters(() => new TestCommand())
         .Positional("IntProp");
     var thePositional = config.DefaultCommand.Positionals[0];
     var thePositionalParameterType = thePositional.GetType().GetGenericArguments()[1];
     Assert.That(thePositionalParameterType, Is.EqualTo(typeof(int)));
 }
 public void PositionalDefinedByNamePrefersCorrectCaseProperty()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Parameters(() => new MultiCaseCommand())
         .Positional("AOne");
     var thePositional = config.DefaultCommand.Positionals[0];
     var thePositionalParameterType = thePositional.GetType().GetGenericArguments()[1];
     Assert.That(thePositionalParameterType, Is.EqualTo(typeof(string)));
 }
 public void InvalidOptionParameterTypeThrows()
 {
     var config = new CommandLineInterpreterConfiguration()
         .Command("test", s => s)
         .Option<XDocument>("opt", (s, x) => { });
 }
 private void Configure(CommandLineInterpreterConfiguration config)
 {
     config.Parameters<Data>()
         .Description("Do something to a file.")
         .Positional("filename")
         .Description("The name of the file.")
         .Option("delete")
         .Alias("D")
         .Description("Delete the file after processing.")
         .Option("archive")
         .Alias("A")
         .Description("Archive after processing");
 }
 public void ACustomParserCanBeSpecifiedOnTheConstructor()
 {
     var config = new CommandLineInterpreterConfiguration(_customParser);
     Assert.That(config.CustomParser, Is.SameAs(_customParser));
 }
        public void SetUp()
        {
            _posix = new CommandLineInterpreterConfiguration(CommandLineParserConventions.PosixConventions);
            _msDos = new CommandLineInterpreterConfiguration(CommandLineParserConventions.MsDosConventions);
            _msStd = new CommandLineInterpreterConfiguration(CommandLineParserConventions.MicrosoftStandard);
            Configure(_posix);
            Configure(_msDos);
            Configure(_msStd);

            _consoleOutInterface = new ConsoleInterfaceForTesting();
            _console = new ConsoleAdapter(_consoleOutInterface);
        }
 public void ACustomParserSetsTheSelectedConvention()
 {
     var config = new CommandLineInterpreterConfiguration(_customParser);
     Assert.That(config.ParserConvention, Is.EqualTo(CommandLineParserConventions.CustomConventions));
 }
Exemplo n.º 27
0
 public void SetUp()
 {
     _config = new CommandLineInterpreterConfiguration();
     _command = _config.Parameters(() => new CommandParams())
         .Positional<string>("pos1", (c, s) => c.Pos1 = s)
         .Positional<int>("pos2", (c, i) => c.Pos2 = i)
         .Option<string, int>("opt1", (c, s, i) =>
         {
             c.Opt1String = s;
             c.Opt1Int = i;
         })
             .Alias("1")
             .Alias("one")
         .Option("opt2", (c, b) => c.Opt2 = b)
             .Alias("2")
             .Alias("two")
         .Option<string>("opt3", (c, s) => c.Opt3 = s)
             .Alias("3")
             .Alias("three");
     _parserResult = new ParserResult(_command, "commandName");
 }
 public void AllowMultipleIsInvalidOnCommands()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Command("x", s => new TestCommand())
             .AllowMultiple();
 }
 public void ShortCircuitOptionOnAPositionalThrows()
 {
     var config = new CommandLineInterpreterConfiguration();
     config
         .Parameters(() => new TestCommand())
         .Description("Description of the whole program.")
         .Positional<string>("pos", (command, s) => { })
             .Description("A positional parameter.")
             .ShortCircuitOption();
 }
 public void DefaultValueIsInvalidOnAnOption()
 {
     var config = new CommandLineInterpreterConfiguration();
     config.Parameters(() => new MultiCaseCommand())
         .Option("AOne").DefaultValue("true");
 }