コード例 #1
0
        private void GetSetting(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput)
        {
            string preferenceName = commandInput.Arguments.Count > 1 ? commandInput.Arguments[1]?.Text : null;

            _telemetry.TrackEvent(new PreferenceEvent("Get", preferenceName));

            //If there's a particular setting to get the value of
            if (!string.IsNullOrEmpty(preferenceName))
            {
                if (_preferences.TryGetValue(preferenceName, out string value))
                {
                    shellState.ConsoleManager.WriteLine(string.Format(Resources.Strings.PrefCommand_Get_ConfiguredValue, value));
                }
                else
                {
                    shellState.ConsoleManager.Error.WriteLine(string.Format(Resources.Strings.PrefCommand_Error_NoConfiguredValue, commandInput.Arguments[1].Text).SetColor(programState.ErrorColor));
                }
            }
            else
            {
                foreach (KeyValuePair <string, string> entry in _preferences.CurrentPreferences.OrderBy(x => x.Key))
                {
                    shellState.ConsoleManager.WriteLine($"{entry.Key}={entry.Value}");
                }
            }
        }
コード例 #2
0
ファイル: Shell.cs プロジェクト: wilvk/HttpRepl
        public Shell(IShellState shellState)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            KeyHandlers.RegisterDefaultKeyHandlers(shellState.InputManager);
            ShellState = shellState;
        }
コード例 #3
0
ファイル: ClearCommand.cs プロジェクト: wilvk/HttpRepl
        public IEnumerable <string> Suggest(IShellState shellState, object programState, ICoreParseResult parseResult)
        {
            parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult));

            if (parseResult.SelectedSection == 0)
            {
                bool nameMatch          = string.IsNullOrEmpty(parseResult.Sections[parseResult.SelectedSection]) || Name.StartsWith(parseResult.Sections[0].Substring(0, parseResult.CaretPositionWithinSelectedSection), StringComparison.OrdinalIgnoreCase);
                bool alternateNameMatch = string.IsNullOrEmpty(parseResult.Sections[parseResult.SelectedSection]) || AlternateName.StartsWith(parseResult.Sections[0].Substring(0, parseResult.CaretPositionWithinSelectedSection), StringComparison.OrdinalIgnoreCase);

                if (nameMatch && alternateNameMatch)
                {
                    return(new[] { Name, AlternateName });
                }
                else if (nameMatch)
                {
                    return(new[] { Name });
                }
                else if (alternateNameMatch)
                {
                    return(new[] { AlternateName });
                }
            }

            return(null);
        }
コード例 #4
0
ファイル: ConnectCommand.cs プロジェクト: scottaddie/HttpRepl
        protected override async Task ExecuteAsync(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput, ICoreParseResult parseResult, CancellationToken cancellationToken)
        {
            commandInput = commandInput ?? throw new ArgumentNullException(nameof(commandInput));

            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            programState = programState ?? throw new ArgumentNullException(nameof(programState));

            string rootAddress        = commandInput.Arguments.SingleOrDefault()?.Text?.EnsureTrailingSlash();
            string baseAddress        = GetBaseAddressFromCommand(commandInput)?.EnsureTrailingSlash();
            string swaggerAddress     = GetSwaggerAddressFromCommand(commandInput);
            bool   isVerbosityEnabled = GetOptionExistsFromCommand(commandInput, VerbosityOption);

            ApiConnection connectionInfo = GetConnectionInfo(shellState, programState, rootAddress, baseAddress, swaggerAddress, _preferences, isVerbosityEnabled);

            bool rootSpecified    = !string.IsNullOrWhiteSpace(rootAddress);
            bool baseSpecified    = !string.IsNullOrWhiteSpace(baseAddress);
            bool openApiSpecified = !string.IsNullOrWhiteSpace(swaggerAddress);

            if (connectionInfo is null)
            {
                _telemetry.TrackEvent(new ConnectEvent(baseSpecified, rootSpecified, openApiSpecified, openApiFound: false));
                return;
            }

            await connectionInfo.SetupHttpState(programState, performAutoDetect : true, cancellationToken);

            bool openApiFound = connectionInfo?.HasSwaggerDocument == true;

            _telemetry.TrackEvent(new ConnectEvent(baseSpecified, rootSpecified, openApiSpecified, openApiFound));

            WriteStatus(shellState, programState);
        }
コード例 #5
0
        public IEnumerable <string> Suggest(IShellState shellState, HttpState programState, ICoreParseResult parseResult)
        {
            if (parseResult.Sections.Count == 0)
            {
                return(new[] { Name });
            }

            if (parseResult.Sections.Count > 0 && parseResult.SelectedSection == 0 && Name.StartsWith(parseResult.Sections[0].Substring(0, parseResult.CaretPositionWithinSelectedSection), StringComparison.OrdinalIgnoreCase))
            {
                return(new[] { Name });
            }

            if (string.Equals(Name, parseResult.Sections[0], StringComparison.OrdinalIgnoreCase) && parseResult.SelectedSection == 1 && (parseResult.Sections.Count < 2 || SubCommand.StartsWith(parseResult.Sections[1].Substring(0, parseResult.CaretPositionWithinSelectedSection), StringComparison.OrdinalIgnoreCase)))
            {
                return(new[] { SubCommand });
            }

            if (parseResult.Sections.Count > 2 &&
                string.Equals(Name, parseResult.Sections[0], StringComparison.OrdinalIgnoreCase) &&
                string.Equals(SubCommand, parseResult.Sections[1], StringComparison.OrdinalIgnoreCase) && parseResult.SelectedSection == 2)
            {
                string prefix = parseResult.Sections[2].Substring(0, parseResult.CaretPositionWithinSelectedSection);
                return(HeaderCompletion.GetCompletions(null, prefix));
            }

            if (parseResult.Sections.Count > 3 &&
                string.Equals(Name, parseResult.Sections[0], StringComparison.OrdinalIgnoreCase) &&
                string.Equals(SubCommand, parseResult.Sections[1], StringComparison.OrdinalIgnoreCase) && parseResult.SelectedSection == 3)
            {
                string prefix = parseResult.Sections[3].Substring(0, parseResult.CaretPositionWithinSelectedSection);
                return(HeaderCompletion.GetValueCompletions(null, string.Empty, parseResult.Sections[2], prefix, programState));
            }

            return(null);
        }
コード例 #6
0
        public Task ExecuteAsync(IShellState shellState, HttpState programState, ICoreParseResult parseResult, CancellationToken cancellationToken)
        {
            if (programState.BaseAddress == null)
            {
                shellState.ConsoleManager.Error.WriteLine("Must be connected to a server to launch Swagger UI".SetColor(programState.ErrorColor));
                return(Task.CompletedTask);
            }

            Uri    uri        = new Uri(programState.BaseAddress, "swagger");
            string agent      = "cmd";
            string agentParam = $"/c start {uri.AbsoluteUri}";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                agent      = "open";
                agentParam = uri.AbsoluteUri;
            }
            else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                agent      = "xdg-open";
                agentParam = uri.AbsoluteUri;
            }

            Process.Start(new ProcessStartInfo(agent, agentParam)
            {
                CreateNoWindow = true
            });
            return(Task.CompletedTask);
        }
コード例 #7
0
        private void SetSetting(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput)
        {
            string prefName  = commandInput.Arguments[1].Text;
            string prefValue = commandInput.Arguments.Count > 2 ? commandInput.Arguments[2]?.Text : null;

            _telemetry.TrackEvent(new PreferenceEvent("Set", prefName));

            if (!_preferences.SetValue(prefName, prefValue))
            {
                shellState.ConsoleManager.Error.WriteLine(Resources.Strings.PrefCommand_Error_Saving.SetColor(programState.ErrorColor));
            }
            else
            {
                // If we think they're configurating HttpRepl to use Visual Studio Code as their editor, we should
                // warn them that for best integration, they should also pass the `-w` or `--wait` arguments to
                // Visual Studio Code.
                if (string.Equals(prefName, WellKnownPreference.DefaultEditorCommand, StringComparison.Ordinal))
                {
                    if (IsVSCode(prefValue))
                    {
                        shellState.ConsoleManager.WriteLine(string.Format(Resources.Strings.PrefCommand_Set_VSCode, WellKnownPreference.DefaultEditorArguments).SetColor(programState.WarningColor));
                    }
                }
            }
        }
コード例 #8
0
        public async Task RunAsync_WithDeleteKeyPress_DeletesCurrentCharacterInTheInputBuffer()
        {
            ConsoleKeyInfo consoleKeyInfo = new ConsoleKeyInfo(keyChar: '\0',
                                                               key: ConsoleKey.Delete,
                                                               shift: false,
                                                               alt: false,
                                                               control: false);
            Shell shell = CreateShell(consoleKeyInfo,
                                      previousCommand: null,
                                      nextCommand: null,
                                      out CancellationTokenSource cancellationTokenSource);

            string inputBufferTextBeforeKeyPress = "get";
            string inputBufferTextAfterKeyPress  = "ge";

            IShellState shellState = shell.ShellState;

            shellState.InputManager.SetInput(shellState, inputBufferTextBeforeKeyPress);

            shellState.ConsoleManager.MoveCaret(2);

            await shell.RunAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            // Verify the input buffer contents after Delete key press event
            Assert.Equal(inputBufferTextAfterKeyPress, shell.ShellState.InputManager.GetCurrentBuffer());
        }
コード例 #9
0
        private void SetInput(IShellState state, IReadOnlyList <char> input, bool moveCaret = true)
        {
            bool oldCaretVisibility = state.ConsoleManager.IsCaretVisible;

            state.ConsoleManager.IsCaretVisible = false;
            int lastCommonPosition = 0;

            for (; lastCommonPosition < input.Count && lastCommonPosition < _inputBuffer.Count && _inputBuffer[lastCommonPosition] == input[lastCommonPosition]; ++lastCommonPosition)
            {
            }

            state.ConsoleManager.MoveCaret(-state.ConsoleManager.CaretPosition + lastCommonPosition);
            string str      = new string(input.Skip(lastCommonPosition).ToArray());
            int    trailing = _inputBuffer.Count - input.Count;

            if (trailing > 0)
            {
                str = str.PadRight(trailing + str.Length);
            }

            state.ConsoleManager.Write(str);

            if (trailing > 0 && moveCaret)
            {
                state.ConsoleManager.MoveCaret(-trailing);
            }

            _inputBuffer.Clear();
            _inputBuffer.AddRange(input);

            if (oldCaretVisibility)
            {
                state.ConsoleManager.IsCaretVisible = true;
            }
        }
コード例 #10
0
ファイル: KeyHandlers.cs プロジェクト: tlmii/HttpRepl
        public static Task Home(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            state = state ?? throw new ArgumentNullException(nameof(state));

            state.MoveCarets(-state.InputManager.CaretPosition);
            return(Task.CompletedTask);
        }
コード例 #11
0
        public async Task RunAsync_WithShiftTabKeyPress_UpdatesInputBufferWithLastEntryFromSuggestionList()
        {
            ConsoleKeyInfo consoleKeyInfo = new ConsoleKeyInfo(keyChar: '\0',
                                                               key: ConsoleKey.Tab,
                                                               shift: true,
                                                               alt: false,
                                                               control: false);
            Shell shell = CreateShell(consoleKeyInfo,
                                      previousCommand: null,
                                      nextCommand: null,
                                      out CancellationTokenSource cancellationTokenSource);

            string inputBufferTextBeforeKeyPress = "c";
            string inputBufferTextAfterKeyPress  = "clear";

            IShellState shellState = shell.ShellState;

            shellState.InputManager.SetInput(shellState, inputBufferTextBeforeKeyPress);

            DefaultCommandDispatcher <object> defaultCommandDispatcher = shellState.CommandDispatcher as DefaultCommandDispatcher <object>;
            string cdCommandName = "cd";

            defaultCommandDispatcher.AddCommand(new MockCommand(cdCommandName));
            string clearCommandName = "clear";

            defaultCommandDispatcher.AddCommand(new MockCommand(clearCommandName));

            await shell.RunAsync(cancellationTokenSource.Token).ConfigureAwait(false);

            // Verify the input buffer contents after Shift + Tab key press event
            Assert.Equal(inputBufferTextAfterKeyPress, shell.ShellState.InputManager.GetCurrentBuffer());
        }
コード例 #12
0
ファイル: KeyHandlers.cs プロジェクト: tlmii/HttpRepl
        public static Task Insert(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            state = state ?? throw new ArgumentNullException(nameof(state));

            state.InputManager.IsOverwriteMode = !state.InputManager.IsOverwriteMode;
            return(Task.CompletedTask);
        }
コード例 #13
0
ファイル: KeyHandlers.cs プロジェクト: tlmii/HttpRepl
        public static Task Delete(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            state = state ?? throw new ArgumentNullException(nameof(state));

            state.InputManager.RemoveCurrentCharacter(state);
            return(Task.CompletedTask);
        }
コード例 #14
0
ファイル: KeyHandlers.cs プロジェクト: tlmii/HttpRepl
        public static Task Escape(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            state = state ?? throw new ArgumentNullException(nameof(state));

            state.InputManager.SetInput(state, string.Empty);
            return(Task.CompletedTask);
        }
コード例 #15
0
ファイル: HelpCommand.cs プロジェクト: tlmii/HttpRepl
        public static void CoreGetHelp(IShellState shellState, ICommandDispatcher <HttpState, ICoreParseResult> dispatcher, HttpState programState)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));

            const int     navCommandColumn = -15;
            StringBuilder output           = new StringBuilder();

            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_SetupCommands.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_SetupCommands_Description);
            output.AppendLine();
            output.AppendLine($"{"connect",navCommandColumn}{GetCommand<ConnectCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"set header",navCommandColumn}{GetCommand<SetHeaderCommand>(dispatcher).GetHelpSummary(shellState, programState)}");

            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_HttpCommands.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_HttpCommands_Description);
            output.AppendLine();
            output.AppendLine($"{"GET",navCommandColumn}{GetCommand<GetCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"POST",navCommandColumn}{GetCommand<PostCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"PUT",navCommandColumn}{GetCommand<PutCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"DELETE",navCommandColumn}{GetCommand<DeleteCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"PATCH",navCommandColumn}{GetCommand<PatchCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"HEAD",navCommandColumn}{GetCommand<HeadCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"OPTIONS",navCommandColumn}{GetCommand<OptionsCommand>(dispatcher).GetHelpSummary(shellState, programState)}");

            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_NavigationCommands.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_NavigationCommands_Description);
            output.AppendLine();

            output.AppendLine($"{"ls",navCommandColumn}{GetCommand<ListCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"cd",navCommandColumn}{GetCommand<ChangeDirectoryCommand>(dispatcher).GetHelpSummary(shellState, programState)}");

            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_ShellCommands.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_ShellCommands_Description);
            output.AppendLine();

            output.AppendLine($"{"clear",navCommandColumn}{GetCommand<ClearCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"echo [on/off]",navCommandColumn}{GetCommand<EchoCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"exit",navCommandColumn}{GetCommand<ExitCommand>(dispatcher).GetHelpSummary(shellState, programState)}");

            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_CustomizationCommands.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_CustomizationCommands_Description);
            output.AppendLine();

            output.AppendLine($"{"pref [get/set]",navCommandColumn}{GetCommand<PrefCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"run",navCommandColumn}{GetCommand<RunCommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine($"{"ui",navCommandColumn}{GetCommand<UICommand>(dispatcher).GetHelpSummary(shellState, programState)}");
            output.AppendLine();
            output.AppendLine(Strings.HelpCommand_Core_Details_Line1.Bold().Cyan());
            output.AppendLine(Strings.HelpCommand_Core_Details_Line2.Bold().Cyan());
            output.AppendLine();

            shellState.ConsoleManager.Write(output.ToString());
        }
コード例 #16
0
        public override string GetHelpSummary(IShellState shellState, HttpState programState)
        {
#pragma warning disable CA1308 // Normalize strings to uppercase
            return($"{Verb.ToLowerInvariant()} - Issues a {Verb.ToUpperInvariant()} request");

#pragma warning restore CA1308 // Normalize strings to uppercase
        }
コード例 #17
0
ファイル: PrefCommand.cs プロジェクト: FeLUXMAJ/DotNetTools
        private static Task SetSetting(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput)
        {
            string prefName  = commandInput.Arguments[1].Text;
            string prefValue = commandInput.Arguments.Count > 2 ? commandInput.Arguments[2]?.Text : null;

            if (string.IsNullOrEmpty(prefValue))
            {
                if (!programState.DefaultPreferences.TryGetValue(prefName, out string defaultValue))
                {
                    programState.Preferences.Remove(prefName);
                }
                else
                {
                    programState.Preferences[prefName] = defaultValue;
                }
            }
            else
            {
                programState.Preferences[prefName] = prefValue;
            }

            if (!programState.SavePreferences())
            {
                shellState.ConsoleManager.Error.WriteLine("Error saving preferences".SetColor(programState.ErrorColor));
            }

            return(Task.CompletedTask);
        }
コード例 #18
0
ファイル: PrefCommand.cs プロジェクト: FeLUXMAJ/DotNetTools
        private static Task GetSetting(IShellState shellState, HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput)
        {
            string preferenceName = commandInput.Arguments.Count > 1 ? commandInput.Arguments[1]?.Text : null;

            //If there's a particular setting to get the value of
            if (!string.IsNullOrEmpty(preferenceName))
            {
                if (programState.Preferences.TryGetValue(preferenceName, out string value))
                {
                    shellState.ConsoleManager.WriteLine("Configured value: " + value);
                }
                else
                {
                    shellState.ConsoleManager.Error.WriteLine((commandInput.Arguments[1].Text + " does not have a configured value").SetColor(programState.ErrorColor));
                }
            }
            else
            {
                foreach (KeyValuePair <string, string> entry in programState.Preferences.OrderBy(x => x.Key))
                {
                    shellState.ConsoleManager.WriteLine($"{entry.Key}={entry.Value}");
                }
            }

            return(Task.CompletedTask);
        }
コード例 #19
0
ファイル: ScriptExecutor.cs プロジェクト: wilvk/HttpRepl
        public async Task ExecuteScriptAsync(IShellState shellState, IEnumerable <string> commandTexts, CancellationToken cancellationToken)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            commandTexts = commandTexts ?? throw new ArgumentNullException(nameof(commandTexts));

            if (shellState.CommandDispatcher is ICommandDispatcher <TProgramState, TParseResult> dispatcher)
            {
                IDisposable suppressor = _hideScriptLinesFromHistory ? shellState.CommandHistory.SuspendHistory() : null;

                using (suppressor)
                {
                    foreach (string commandText in commandTexts)
                    {
                        if (string.IsNullOrWhiteSpace(commandText))
                        {
                            continue;
                        }

                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }

                        dispatcher.OnReady(shellState);
                        shellState.ConsoleManager.ResetCommandStart();
                        shellState.InputManager.SetInput(shellState, commandText);
                        await dispatcher.ExecuteCommandAsync(shellState, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
        }
コード例 #20
0
ファイル: KeyHandlers.cs プロジェクト: jimmylewis/HttpRepl
        public static Task DownArrow(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            string line = state.CommandHistory.GetNextCommand();

            state.InputManager.SetInput(state, line);
            return(Task.CompletedTask);
        }
コード例 #21
0
        protected override Task ExecuteAsync(IShellState shellState, object programState, DefaultCommandInput <ICoreParseResult> commandInput, ICoreParseResult parseResult, CancellationToken cancellationToken)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            shellState.IsExiting = true;
            return(Task.CompletedTask);
        }
コード例 #22
0
ファイル: KeyHandlers.cs プロジェクト: jimmylewis/HttpRepl
        public static Task LeftArrow(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            if (state.ConsoleManager.CaretPosition > 0)
            {
                if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
                {
                    state.ConsoleManager.MoveCaret(-1);
                }
                else
                {
                    string           line        = state.InputManager.GetCurrentBuffer();
                    ICoreParseResult parseResult = state.CommandDispatcher.Parser.Parse(line, state.ConsoleManager.CaretPosition);
                    int targetSection            = parseResult.SelectedSection - (parseResult.CaretPositionWithinSelectedSection > 0 ? 0 : 1);

                    if (targetSection < 0)
                    {
                        targetSection = 0;
                    }

                    int desiredPosition = parseResult.SectionStartLookup[targetSection];
                    state.ConsoleManager.MoveCaret(desiredPosition - state.ConsoleManager.CaretPosition);
                }
            }

            return(Task.CompletedTask);
        }
コード例 #23
0
ファイル: KeyHandlers.cs プロジェクト: jimmylewis/HttpRepl
        public static Task RightArrow(ConsoleKeyInfo keyInfo, IShellState state, CancellationToken cancellationToken)
        {
            string line = state.InputManager.GetCurrentBuffer();

            if (state.ConsoleManager.CaretPosition < line.Length)
            {
                if (!keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
                {
                    state.ConsoleManager.MoveCaret(1);
                }
                else
                {
                    ICoreParseResult parseResult = state.CommandDispatcher.Parser.Parse(line, state.ConsoleManager.CaretPosition);
                    int targetSection            = parseResult.SelectedSection + 1;

                    if (targetSection >= parseResult.Sections.Count)
                    {
                        state.ConsoleManager.MoveCaret(line.Length - state.ConsoleManager.CaretPosition);
                    }
                    else
                    {
                        int desiredPosition = parseResult.SectionStartLookup[targetSection];
                        state.ConsoleManager.MoveCaret(desiredPosition - state.ConsoleManager.CaretPosition);
                    }
                }
            }

            return(Task.CompletedTask);
        }
コード例 #24
0
ファイル: ConnectCommand.cs プロジェクト: vijayraavi/HttpRepl
        private static bool SetupBaseAddress(IShellState shellState, string baseAddress, ApiConnection connectionInfo)
        {
            if (!string.IsNullOrWhiteSpace(baseAddress))
            {
                if (!connectionInfo.HasRootUri && !Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute))
                {
                    shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_NoRootNoAbsoluteBase);
                    return(false);
                }
                else if (connectionInfo.HasRootUri && !Uri.IsWellFormedUriString(baseAddress, UriKind.RelativeOrAbsolute))
                {
                    shellState.ConsoleManager.Error.WriteLine(Resources.Strings.ConnectCommand_Error_InvalidBase);
                    return(false);
                }

                if (Uri.IsWellFormedUriString(baseAddress, UriKind.Absolute))
                {
                    connectionInfo.BaseUri = new Uri(baseAddress, UriKind.Absolute);
                }
                else if (Uri.IsWellFormedUriString(baseAddress, UriKind.Relative))
                {
                    connectionInfo.BaseUri = new Uri(connectionInfo.RootUri, baseAddress);
                }
            }

            return(true);
        }
コード例 #25
0
        public async Task ExecuteAsync_WithoutHistoryOption_AvoidsAddingCommandsExecutedFromScriptToCommandHistory()
        {
            string commands = @"set header name value1 value2";

            if (!File.Exists(_pathToScript))
            {
                File.WriteAllText(_pathToScript, commands);
            }

            string parseResultSections = "run " + _pathToScript;

            ArrangeInputs(parseResultSections: parseResultSections,
                          out MockedShellState _,
                          out HttpState httpState,
                          out ICoreParseResult parseResult);

            IShellState      shellState       = GetShellState(commands, httpState);
            MockedFileSystem mockedFileSystem = new MockedFileSystem();

            mockedFileSystem.AddFile(_pathToScript, commands);
            RunCommand runCommand = new RunCommand(mockedFileSystem);

            await runCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            string previousCommand = shellState.CommandHistory.GetPreviousCommand();

            Assert.True(string.IsNullOrEmpty(previousCommand));
        }
コード例 #26
0
        public bool?CanHandle(IShellState shellState, TProgramState programState, TParseResult parseResult)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            if (!DefaultCommandInput <TParseResult> .TryProcess(InputSpec, parseResult, out DefaultCommandInput <TParseResult> commandInput, out IReadOnlyList <CommandInputProcessingIssue> processingIssues))
            {
                //If this is the right command, just not the right syntax, report the usage errors
                if (processingIssues.All(x => x.Kind != CommandInputProcessingIssueKind.CommandMismatch))
                {
                    foreach (CommandInputProcessingIssue issue in processingIssues)
                    {
                        shellState.ConsoleManager.Error.WriteLine(GetStringForIssue(issue));
                    }

                    string help = GetHelpDetails(shellState, programState, parseResult);
                    shellState.ConsoleManager.WriteLine(help);
                    return(false);
                }

                //If there was a mismatch in the command name, this isn't our input to handle
                return(null);
            }

            return(CanHandle(shellState, programState, commandInput));
        }
コード例 #27
0
        public async Task ExecuteAsync(IShellState shellState, HttpState programState, ICoreParseResult parseResult, CancellationToken cancellationToken)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            programState = programState ?? throw new ArgumentNullException(nameof(programState));

            parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult));

            if (parseResult.Sections.Count == 2)
            {
                programState.BaseAddress = null;
            }
            else if (parseResult.Sections.Count != 3 || string.IsNullOrEmpty(parseResult.Sections[2]) || !Uri.TryCreate(parseResult.Sections[2].EnsureTrailingSlash(), UriKind.Absolute, out Uri serverUri))
            {
                shellState.ConsoleManager.Error.WriteLine(Strings.SetBaseCommand_MustSpecifyServerError.SetColor(programState.ErrorColor));
            }
            else
            {
                programState.BaseAddress = serverUri;
                try
                {
                    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, serverUri))
                    {
                        await programState.Client.SendAsync(request).ConfigureAwait(false);
                    }
                }
                catch (Exception ex) when(ex.InnerException is SocketException se)
                {
                    shellState.ConsoleManager.Error.WriteLine(String.Format(Strings.SetBaseCommand_HEADRequestUnSuccessful, se.Message).SetColor(programState.WarningColor));
                }
                catch { }
            }
        }
コード例 #28
0
ファイル: ClearCommand.cs プロジェクト: wilvk/HttpRepl
        public Task ExecuteAsync(IShellState shellState, object programState, ICoreParseResult parseResult, CancellationToken cancellationToken)
        {
            shellState = shellState ?? throw new ArgumentNullException(nameof(shellState));

            shellState.ConsoleManager.Clear();
            shellState.CommandDispatcher.OnReady(shellState);
            return(Task.CompletedTask);
        }
コード例 #29
0
        public bool?CanHandle(IShellState shellState, HttpState programState, ICoreParseResult parseResult)
        {
            parseResult = parseResult ?? throw new ArgumentNullException(nameof(parseResult));

            return(parseResult.ContainsAtLeast(minimumLength: 2, Name) && parseResult.Sections.Count < 4
                ? (bool?)true
                : null);
        }
コード例 #30
0
        public void SetInput(IShellState state, string input)
        {
            state = state ?? throw new ArgumentNullException(nameof(state));

            input = input ?? throw new ArgumentNullException(nameof(input));

            SetInput(state, input.ToCharArray());
        }