public void formatting_help_command_with_console_formatter(IHelpFormatter formatter, ICommandHelp commandHelp, string result)
        {
            "Given I have a console formatter"
            ._(() => formatter = ServiceLocator.Resolve <ConsoleHelpFormatter>());

            "And I have a help command"
            ._(() => commandHelp = new CommandHelp("init", "Crane.Core.Commands.Init", "Initializes a new project with foo and bar.", new[] { new CommandExample {
                                                                                                                                                  Value = "Example 1"
                                                                                                                                              } }));

            "When I format the command"
            ._(() => result = formatter.Format(commandHelp));

            "It should display the usage statement on the first line"
            ._(() => result.Line(0).Should().Be("usage: crane init <project name>"));

            "It should display the description statement on the 3rd line"
            ._(() => result.Line(2).Should().Be("Initializes a new project with foo and bar."));

            "It should display the example"
            ._(() => result.Line(4).Should().Be("Example 1"));

            "It should display for information url"
            ._(() => result.Line(6).Should().Contain("For more information, visit"));
        }
Beispiel #2
0
 public GenDocCommandHandler(IFileManager fileManager, IPublicCommandResolver commandResolver, IHelpProvider helpProvider, MarkdownHelpFormatter helpFormatter)
 {
     _fileManager   = fileManager;
     _helpProvider  = helpProvider;
     _helpFormatter = helpFormatter;
     _commands      = commandResolver.Resolve().OrderBy(command => command.Name());
 }
        /// <summary>
        /// Prints help for all possible commands in the specified types
        /// </summary>
        /// <param name="types">List of types in which to get all assemblies, or nothing to scan all assembly</param>
        /// <param name="helpFormatter">Help formatting engine, or nothing to format the messages to console</param>
        /// <param name="configurationBuilder">Configuration builder action, or nothing to use defaults</param>
        public static void PrintHelp(Type[] types, IHelpFormatter helpFormatter = null, Action <Parser.Configuration> configurationBuilder = null)
        {
            // Extract available commands based on information gathered & print help
            var configuration = Parse(types, configurationBuilder);

            PrintHelpInternal(configuration, null, helpFormatter, new Operation.Items(new Operation.OperationResult()), false);
        }
Beispiel #4
0
        /// <summary>
        /// Executes the command
        /// </summary>
        /// <param name="args">List of arguments</param>
        /// <param name="operationResult">Operation result to write in</param>
        /// <param name="helpFormatter">Formatter object in case we need to write help</param>
        /// <returns>Results from execution</returns>
        public OperationExecutionResult Execute(string[] args, IHelpFormatter helpFormatter = null)
        {
            var operationResult = new Operation.OperationExecutionResult();

            ExecuteInternal(args, operationResult);
            return(operationResult);
        }
Beispiel #5
0
        public void formatting_help_command_with_console_formatter(IHelpFormatter formatter, ICommandHelp commandHelp, string result)
        {
            "Given I have a markdown formatter"
            ._(() => formatter = ServiceLocator.Resolve <MarkdownHelpFormatter>());

            "And I have a help command"
            ._(() => commandHelp = new CommandHelp("init", "Crane.Core.Commands.Init",
                                                   "Initializes a new project with foo and bar.",
                                                   new[] { new CommandExample {
                                                               Value = "Example 1\n<code>usage</code>\n<code>\nvar x = 1;\nvar y=2;\n</code>"
                                                           } }));

            "When I format the command"
            ._(() => result = formatter.Format(commandHelp));

            "Then it should display the usage statement on the first line"
            ._(() => result.Line(0).Should().Be("`usage: crane init <project name>`"));

            "And it should display the description statement on the 3rd line"
            ._(() => result.Line(2).Should().Be("Initializes a new project with foo and bar."));

            "And it should display the first line of an example as a title"
            ._(() => result.Lines().First(item => item.Contains("Example"))
               .Should().StartWith("**")
               .And.EndWith("**  "));

            "And it should display any code element values that start and begin on the same line as markdown code blocks using single back ticks"
            ._(() => result.Should().Contain("`usage`"));

            "And it should display any multiline code blocks as markdown code blocks"
            ._(
                () =>
                result.Should().Contain(string.Format("```{0}var x = 1;{0}var y=2;{0}```", Environment.NewLine)));
        }
Beispiel #6
0
        /// <summary>
        /// A helper method for getting the formatted help text into a string
        /// </summary>
        /// <param name="source">The implemented help formatter</param>
        /// <param name="modelHelp">The data structure that contains the help information</param>
        /// <returns></returns>
        public static string GetHelp(this IHelpFormatter source, ModelHelp modelHelp)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                source.WriteHelp(modelHelp, writer);
            }

            return(builder.ToString());
        }
        internal static void PrintHelpInternal(Parser.Configuration configuration, Parser.Command command, IHelpFormatter helpFormatter, Operation.Items operationMessages, bool error = true)
        {
            var f    = (helpFormatter ?? new Formatters.Console());
            var exit = (f as Formatters.FormatterBase)?.ExitOnError ?? true;

            // Print help using the help formatter, or create a default console messenger for this
            f.PrintHelp(configuration, command, operationMessages);
            PrintDebug(operationMessages);

            if (error && exit)
            {
                Environment.Exit(Int32.MinValue);
            }
        }
 /// <summary>
 /// Prints help for all possible commands in the specified types
 /// </summary>
 /// <param name="type">Types in which to get all assemblies, or nothing to scan all assembly</param>
 /// <param name="helpFormatter">Help formatting engine, or nothing to format the messages to console</param>
 /// <param name="configurationBuilder">Configuration builder action, or nothing to use defaults</param>
 public static void PrintHelp(Type type, IHelpFormatter helpFormatter = null, Action <Parser.Configuration> configurationBuilder = null)
 {
     PrintHelp(new[] { type }, helpFormatter, configurationBuilder);
 }
 public static void PrintHelp(this IHelpFormatter formatter, Options options, TextWriter writer)
 {
     PrintHelp(formatter, options, writer, false);
 }
 public static void PrintHelpToConsole(this IHelpFormatter formatter, Options options, bool autoUsage)
 {
     formatter.PrintHelp(options, Console.Out, autoUsage);
 }
 public static void PrintHelpToConsole(this IHelpFormatter formatter, Options options)
 {
     PrintHelpToConsole(formatter, options, false);
 }
 public static void PrintHelp(this IHelpFormatter formatter, Options options, TextWriter writer, bool autoUsage)
 {
     formatter.PrintHelp(options, new HelpSettings(), writer, autoUsage);
 }
Beispiel #13
0
        /// <summary>
        /// Executes the command passed in the arguments
        /// </summary>
        /// <param name="args">List of retrieved arguments, or null to extract the arguments from the Environment</param>
        /// <param name="types">List of types in which to get all assemblies, or nothing to scan all assembly</param>
        /// <param name="helpFormatter">Help formatting engine, or nothing to format the messages to console</param>
        /// <param name="configurationBuilder">Configuration builder action, or nothing to use defaults</param>
        /// <returns>Results from the operation</returns>
        public static Operation.OperationExecutionResult Execute(string[] args, Type[] types, IHelpFormatter helpFormatter = null, Action <Parser.Configuration> configurationBuilder = null)
        {
            // Get safe args collection
            args = GetSafeArgs(args);

            // Extract available commands based on information gathered
            var configuration = CommandParser.Parse(types, configurationBuilder);

            // Start logging operation
            var operationResult = new Operation.OperationExecutionResult();

            // Get command from arguments
            operationResult.Messages.Add(new Operation.Messages.Progress(Resources.GetFromArguments));
            var command       = configuration.GetCommand(args);
            var requestedHelp = configuration.GetArgumentHelp(args);

            operationResult.Messages.Add(new Operation.Messages.Information(String.Format(Resources.CommandInformation, (command == null ? "Unknown" : command.Name), requestedHelp)));

            // User requested help
            if (requestedHelp)
            {
                CommandParser.PrintHelpInternal(configuration, command, helpFormatter, operationResult.Messages, false);
                return(operationResult);
            }

            // We could not get a command, but there is only one that exists, so we can try to execute it
            if (command == null && configuration.Commands.Count() == 1)
            {
                command = configuration.Commands.First();
                operationResult.Messages.Add(new Operation.Messages.Information(String.Format(Resources.UnknownCommandSingle, command.Name)));
                command.ExecuteInternal(args, operationResult, helpFormatter);
                return(operationResult);
            }

            // Otherwise, execute from arguments
            if (command != null)
            {
                operationResult.Messages.Add(new Operation.Messages.Information(String.Format(Resources.ExecutingCommandFromArguments, command.Name)));
                command.ExecuteInternal(args, operationResult, helpFormatter);
                return(operationResult);
            }
            else
            {
                operationResult.Messages.Add(new Operation.Messages.Error(Resources.UnknownCommand));
                CommandParser.PrintHelpInternal(configuration, null, helpFormatter, operationResult.Messages);
                return(operationResult);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Executes the command passed in the arguments
 /// </summary>
 /// <param name="args">List of retrieved arguments, or null to extract the arguments from the Environment</param>
 /// <param name="type">Type in which to get all assemblies, or nothing to scan all assembly</param>
 /// <param name="helpFormatter">Help formatting engine, or nothing to format the messages to console</param>
 /// <param name="configurationBuilder">Configuration builder action, or nothing to use defaults</param>
 /// <returns>Results from the operation</returns>
 public static Operation.OperationExecutionResult Execute(string[] args, Type type, IHelpFormatter helpFormatter = null, Action <Parser.Configuration> configurationBuilder = null)
 {
     return(Execute(args, new[] { type }, helpFormatter, configurationBuilder));
 }
Beispiel #15
0
 public HelpCommandHandler(IOutput output, IHelpProvider helpProvider, IHelpFormatter helpFormatter)
 {
     _output        = output;
     _helpProvider  = helpProvider;
     _helpFormatter = helpFormatter;
 }
Beispiel #16
0
        /// <summary>
        /// Executes the command
        /// </summary>
        /// <param name="args">List of arguments</param>
        /// <param name="operationResult">Operation result to write in</param>
        /// <param name="helpFormatter">Formatter object in case we need to write help</param>
        internal void ExecuteInternal(string[] args, OperationExecutionResult operationResult, IHelpFormatter helpFormatter = null)
        {
            var parsedArguments = ValidateInternal(args, operationResult);

            if (!operationResult.Valid)
            {
                CommandParser.PrintHelpInternal(Configuration, this, helpFormatter, operationResult.Messages);
                return;
            }

            try
            {
                operationResult.Messages.Add(new Operation.Messages.Progress(String.Format(Resources.ExecutingCommand, Name)));

                // Create instance of reflected type
                var target = (object)null;
                if (!MethodInfo.IsStatic)
                {
                    // No check, if it crashes it crashes
                    operationResult.Messages.Add(new Operation.Messages.Warning(String.Format(Resources.CreatingDefaultInstance, MethodInfo.DeclaringType)));
                    target = Activator.CreateInstance(MethodInfo.DeclaringType, true);
                }

                // Get values
                var allParameters = SystemParameters.Concat(Parameters).OrderBy(i => i.ParameterInfo.Position);
                var values        = allParameters.Select(i =>
                {
                    if (typeof(InputArguments).GetTypeInfo().IsAssignableFrom(i.ParameterInfo.ParameterType))
                    {
                        return(parsedArguments);
                    }
                    else if (typeof(OperationResult).GetTypeInfo().IsAssignableFrom(i.ParameterInfo.ParameterType))
                    {
                        return(operationResult);
                    }
                    else if (typeof(Array).GetTypeInfo().IsAssignableFrom(i.ParameterInfo.ParameterType))
                    {
                        var finalType   = i.ParameterInfo.ParameterType.GetElementType();
                        var objectArray = parsedArguments.GetValue(i)
                                          .Select(j => Convert.ChangeType(j, finalType))
                                          .ToArray();
                        var arr = Array.CreateInstance(finalType, objectArray.Length);
                        Array.Copy(objectArray, arr, objectArray.Length);
                        return(arr);
                    }
                    else
                    {
                        return(Convert.ChangeType(parsedArguments.GetValue(i)[0], i.ParameterInfo.ParameterType));
                    }
                })
                                    .ToArray();

                operationResult.Output = MethodInfo.Invoke(target, values);
            }
            catch (Exception e)
            {
                throw new CommandLineEngineException(Resources.ErrorExecutingCommand, operationResult, e);
            }
            finally
            {
                CommandParser.PrintDebug(operationResult.Messages);
            }
        }