Exemplo n.º 1
0
        /// <summary>
        /// Runs the application with specified command line and environment variables, and returns the exit code.
        /// </summary>
        /// <remarks>
        /// If a <see cref="CommandException"/>, <see cref="DirectiveException"/>, or <see cref="TypinException"/> is thrown during command execution,
        /// it will be handled and routed to the console. Additionally, if the debugger is not attached (i.e. the app is running in production),
        /// all other exceptions thrown within this method will be handled and routed to the console as well.
        /// </remarks>
        public async ValueTask <int> RunAsync(string commandLine, IReadOnlyDictionary <string, string> environmentVariables, bool containsExecutable = false)
        {
            IEnumerable <string> commandLineArguments = CommandLineSplitter.Split(commandLine)
                                                        .Skip(containsExecutable ? 1 : 0);

            return(await RunAsync(commandLineArguments, environmentVariables));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets user input and returns arguments or null if cancelled.
        /// </summary>
        private async Task <IEnumerable <string> > GetInputAsync(string executableName)
        {
            IConsole console = _console;

            // Print prompt
            ConsoleColor promptForeground = _options.PromptForeground;

            console.Output.WithForegroundColor(promptForeground, (output) => output.Write(executableName));

            string scope    = _options.Scope;
            bool   hasScope = !string.IsNullOrWhiteSpace(scope);

            if (hasScope)
            {
                console.Output.WithForegroundColor(_options.ScopeForeground, (output) =>
                {
                    output.Write(' ');
                    output.Write(scope);
                });
            }

            console.Output.WithForegroundColor(promptForeground, (output) => output.Write("> "));

            // Read user input
            console.ForegroundColor = _options.CommandForeground;

            string?line = string.Empty;  // Can be null when Ctrl+C is pressed to close the app.

            if (_autoCompleteInput is null)
            {
                line = await console.Input.ReadLineAsync();
            }
            else
            {
                line = await _autoCompleteInput.ReadLineAsync(console.GetCancellationToken());
            }

            console.ForegroundColor = ConsoleColor.Gray;

            IEnumerable <string> arguments = Enumerable.Empty <string>();

            if (!string.IsNullOrWhiteSpace(line))
            {
                if (hasScope) // handle scoped command input
                {
                    List <string> tmp = CommandLineSplitter.Split(line).ToList();

                    int lastDirective = tmp.FindLastIndex(x => x.StartsWith('[') && x.EndsWith(']'));
                    tmp.Insert(lastDirective + 1, scope);

                    arguments = tmp.ToArray();
                }
                else // handle unscoped command input
                {
                    arguments = CommandLineSplitter.Split(line);
                }
            }

            return(arguments);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs the application with specified command line and returns the exit code.
        /// Environment variables are retrieved automatically.
        /// </summary>
        /// <remarks>
        /// If a <see cref="CommandException"/>, <see cref="DirectiveException"/>, or <see cref="TypinException"/> is thrown during command execution,
        /// it will be handled and routed to the console. Additionally, if the debugger is not attached (i.e. the app is running in production),
        /// all other exceptions thrown within this method will be handled and routed to the console as well.
        /// </remarks>
        public async ValueTask <int> RunAsync(string commandLine, bool containsExecutable = false)
        {
            IEnumerable <string> commandLineArguments = CommandLineSplitter.Split(commandLine)
                                                        .Skip(containsExecutable ? 1 : 0);

            return(await RunAsync(commandLineArguments));
        }
Exemplo n.º 4
0
        public void CLS001(string commandLine, string expectedCommand, string expectedArguments)
        {
            // arrange, act
            var result = CommandLineSplitter.Split(commandLine);

            // assert
            result.Command.Should().Be(expectedCommand);
            result.Arguments.Should().Be(expectedArguments);
        }
Exemplo n.º 5
0
        public void ShouldParse(string commandLine, string[] results)
        {
            //Act
            IEnumerable <string> splitted = CommandLineSplitter.Split(commandLine);

            //Assert
            splitted.Count().Should().Be(results.Length);
            splitted.Should().Equal(results);
        }
Exemplo n.º 6
0
        private void VerifyCommandLineSplitter(string commandLine, string[] expected)
        {
            string[] actual = CommandLineSplitter.SplitCommandLine(commandLine);

            Assert.Equal(expected.Length, actual.Length);
            for (int i = 0; i < actual.Length; ++i)
            {
                Assert.Equal(expected[i], actual[i]);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Runs the application and returns the exit code.
        /// Command line arguments and environment variables are retrieved automatically.
        /// </summary>
        /// <remarks>
        /// If a <see cref="CommandException"/> is thrown during command execution, it will be handled and routed to the console.
        /// Additionally, if the debugger is not attached (i.e. the app is running in production), all other exceptions thrown within
        /// this method will be handled and routed to the console as well.
        /// </remarks>
        public async ValueTask <int> RunAsync()
        {
            string line = Environment.CommandLine;

            string[] commandLineArguments = CommandLineSplitter.Split(line)
                                            .Skip(1)
                                            .ToArray();

            return(await RunAsync(commandLineArguments));
        }
Exemplo n.º 8
0
        public void ShouldParse(string commandLine, string[] results)
        {
            //Act
            IEnumerable <string> split = CommandLineSplitter.Split(commandLine);

            _output.WriteLine(commandLine);
            _output.WriteLine(JsonConvert.SerializeObject(split));

            //Assert
            split.Count().Should().Be(results.Length);
            split.Should().Equal(results);
        }
Exemplo n.º 9
0
        public static void TestCommandLineParser(ICommandLineParser parser, CommandLineSplitter splitter, string line, CommandLineItem[] expectedItems)
        {
            var _commandLine = splitter.ParseString(line);
            var _actualItems = parser.ParseCommandLine(_commandLine);

            for (var _i = 0; _i < expectedItems.Length && _i < _actualItems.Count; _i++)
            {
                Assert.Equal(expectedItems[_i].ToString(), _actualItems[_i].ToString(), StringComparer.Ordinal);
                Assert.Equal(expectedItems[_i], _actualItems[_i]);
            }

            Assert.Equal(expectedItems.Length, _actualItems.Count);
            Assert.True(expectedItems.SequenceEqual(_actualItems));

            Assert.Equal(_commandLine.Value, splitter.ParseString(_commandLine.Value).Value);
        }
Exemplo n.º 10
0
        public static void CommandLineIsSplittedLikeWin32Does(string line, CommandLineSplitter parser)
        {
            var _commandLine  = parser.ParseString(line);
            var _actualArgs   = _commandLine.GetArgs();
            var _expectedArgs = Win32CommandLineToArgvW.Split(line);

            Assert.True(_commandLine.Equals(_expectedArgs));
            Assert.False(_commandLine.Equals(_expectedArgs.Concat(new[] { string.Empty }).ToArray()));
            Assert.Equal(string.Join(Environment.NewLine, _expectedArgs), string.Join(Environment.NewLine, _actualArgs));
            Assert.Equal(_expectedArgs.Length, _commandLine.Parts.Count);
            for (var _i = 0; _i < _expectedArgs.Length; _i++)
            {
                Assert.Equal(_i, _commandLine.Parts[_i].Index);
                Assert.Equal(_expectedArgs[_i], _commandLine.Parts[_i].Value);
                Assert.True(_commandLine.Parts[_i].Equals(_expectedArgs[_i]));
            }

            Assert.Equal(_commandLine.Value, parser.ParseString(_commandLine.Value).Value);
        }
Exemplo n.º 11
0
        private string[]? GetInput(IConsole console, string executableName)
        {
            string[] arguments;
            string?  line = string.Empty; // Can be null when Ctrl+C is pressed to close the app.

            do
            {
                // Print prompt
                console.WithForegroundColor(_promptForeground, () =>
                {
                    console.Output.Write(executableName);
                });

                if (!string.IsNullOrWhiteSpace(CliContext.Scope))
                {
                    console.WithForegroundColor(ConsoleColor.Cyan, () =>
                    {
                        console.Output.Write(' ');
                        console.Output.Write(CliContext.Scope);
                    });
                }

                console.WithForegroundColor(_promptForeground, () =>
                {
                    console.Output.Write("> ");
                });

                // Read user input
                console.WithForegroundColor(_commandForeground, () =>
                {
                    if (_autoCompleteInput is null)
                    {
                        line = console.Input.ReadLine();
                    }
                    else
                    {
                        line = _autoCompleteInput.ReadLine();
                    }
                });

                if (line is null)
                {
                    return(null);
                }

                if (string.IsNullOrWhiteSpace(CliContext.Scope)) // handle unscoped command input
                {
                    arguments = CommandLineSplitter.Split(line)
                                .Where(x => !string.IsNullOrWhiteSpace(x))
                                .ToArray();
                }
                else // handle scoped command input
                {
                    List <string> tmp = CommandLineSplitter.Split(line)
                                        .Where(x => !string.IsNullOrWhiteSpace(x))
                                        .ToList();

                    int lastDirective = tmp.FindLastIndex(x => x.StartsWith('[') && x.EndsWith(']'));
                    tmp.Insert(lastDirective + 1, CliContext.Scope);

                    arguments = tmp.ToArray();
                }
            } while (string.IsNullOrWhiteSpace(line)); // retry on empty line

            console.ForegroundColor = ConsoleColor.Gray;

            return(arguments);
        }
Exemplo n.º 12
0
 public static bool ParseArgs(string argString)
 {
     return(ParseArgs(CommandLineSplitter.SplitArguments(argString)));
 }
Exemplo n.º 13
0
 public static void RunCommand(string argString)
 {
     RunCommand(CommandLineSplitter.SplitArguments(argString));
 }