Beispiel #1
0
        static async Task Main()
        {
            Console.WriteLine("Dual Numbers 1.0\n1D function must starts from 't =>'\n3D function must starts from 'p =>'");
            Console.WriteLine("Examples:\nSqrt(2*2)\nt => Sin(t)\nt => Vec(1, 2, t)\np => p^Vec(0, 0, 1)");
            ReadLine.AddHistory("Sqrt(2*2)", "t => Sin(t)", "t => Vec(1, 2, t)", "p => p^Vec(0, 0, 1)");

            while (true)
            {
                try
                {
                    var code = ReadLine.Read("(prompt)> ");
                    if (code.StartsWith("t =>"))
                    {
                        await Func <DualNumber>(code);
                    }
                    else if (code.StartsWith("p =>"))
                    {
                        await Func <DualVectorGrad>(code);
                    }
                    else
                    {
                        await Expr(code);
                    }
                }
                catch (Exception ex)
                {
                    PrintError(ex);
                }
            }
        }
Beispiel #2
0
        public static void Main(string[] args)
        {
            Console.WriteLine("ReadLine Library Demo");
            Console.WriteLine("---------------------");
            Console.WriteLine();

            string[] history = new string[] { "ls -a", "dotnet run", "git init" };
            ReadLine.AddHistory(history);

            ReadLine.AutoCompletionHandler = (t, s) =>
            {
                if (t.StartsWith("git "))
                {
                    return new string[] { "init", "clone", "pull", "push" }
                }
                ;
                else
                {
                    return(null);
                }
            };

            string input = ReadLine.Read("(prompt)> ");

            Console.Write(input);
        }
Beispiel #3
0
        public void UpdateHistory(string statement)
        {
            try
            {
                if (!File.Exists(HistoryFilePath))
                {
                    File.Create(HistoryFilePath).Dispose();
                }

                if (!SecuredCommands.Any(statement.Contains))
                {
                    List <string> history = ReadLine.GetHistory();
                    if (history.LastOrDefault() != statement)
                    {
                        ReadLine.AddHistory(statement);
                        _historyCloned.Insert(0, statement);
                    }
                }
                else
                {
                    ReadLine.AddHistory(_removedString);
                    _historyCloned.Insert(0, statement);
                }

                File.WriteAllLines(HistoryFilePath, _historyCloned.Distinct().Reverse().ToArray());
            }
            catch (Exception e)
            {
                if (writeFailNotReported)
                {
                    writeFailNotReported = false;
                    _cliConsole.WriteErrorLine($"Could not write cmd history to {HistoryFilePath} {e.Message}");
                }
            }
        }
Beispiel #4
0
        public static async Task <string> Readline(WorkItemManager manager, WorkItem wi, PropertyDescriptor propertyDescriptor, string currentValue)
        {
            ReadLine.ClearHistory();
            ReadLine.AutoCompletionHandler = null;

            if (propertyDescriptor.ValueProvider != null)
            {
                var valueProvider = manager.ValidationManager.CreateValueProvider(wi, propertyDescriptor.ValueProvider);
                if (valueProvider.IsUserExpierenceEnumerable)
                {
                    foreach (var providedValue in await valueProvider.ProvideAllValuesAsync())
                    {
                        ReadLine.AddHistory(providedValue.Value);
                    }
                }

                ReadLine.AutoCompletionHandler = new ValueProviderReadLineAutoCompletion(valueProvider);
            }

            string result;

            if (string.IsNullOrWhiteSpace(currentValue))
            {
                result = ReadLine.Read($"{propertyDescriptor.Name}: ");
            }
            else
            {
                result = ReadLine.Read($"{propertyDescriptor.Name} [{currentValue}]: ");
            }

            return(result);
        }
Beispiel #5
0
        private static void StartingMainLoop()
        {
            // System.Console.WriteLine("Strating main loop");
            keyEventCts?.Cancel();
            mainCts = new CancellationTokenSource();
            var mainToken = mainCts.Token;

            Task.Factory.StartNew(() =>
            {
                while (!mainToken.IsCancellationRequested)
                {
                    try
                    {
                        string input = ReadLine.Read(PROMPT_TITLE);
                        if (!string.IsNullOrEmpty(input) || !string.IsNullOrWhiteSpace(input))
                        {
                            GenerateCommands();
                            ReadLine.AddHistory(input);
                            app.Execute(input.Split(' ').ToArray());
                        }
                    }
                    catch
                    {
                    }
                }
            }, mainToken);
        }
Beispiel #6
0
        public static string RedPeanutCLI(IAgentInstance agent, string module)
        {
            string input;

            if (agent == null)
            {
                PrintCLI(module);
                input = ReadLine.Read();

                if (input.Trim().Length > 0)
                {
                    ReadLine.AddHistory(input);
                }

                return(input);
            }
            else
            {
                PrintCLI(agent.AgentId, module);
                input = ReadLine.Read();
                StandardCommand cmd = new StandardCommand(agent);
                if (cmd.Execute(input))
                {
                    input = "";
                }

                if (input.Trim().Length > 0)
                {
                    ReadLine.AddHistory(input);
                }

                return(input);
            }
        }
Beispiel #7
0
        static string ReadQuery()
        {
            StringBuilder sb = new StringBuilder();
            string        line;

            while (true)
            {
                if ((line = System.ReadLine.Read()) == null)
                {
                    sb.Length = 0;

                    break;
                }
                else
                {
                    sb.AppendLine(line);

                    if (line.EndsWith("/") || line.StartsWith("!") || line.EndsWith("."))
                    {
                        break;
                    }

                    Console.Write("|  ");
                }
            }

            ReadLine.AddHistory(sb.ToString().TrimEnd(Environment.NewLine.ToCharArray()));
            return(sb.ToString());
        }
        public static string Read(string promt)
        {
            var line = ReadInternal(promt);

            ReadLine.AddHistory(line);

            return(line);
        }
Beispiel #9
0
        public void StartRepl()
        {
            _screenManager.PrintHeader();
            _screenManager.PrintUsage();
            _screenManager.PrintLine();

            ReadLine.AutoCompletionHandler = new AutoCompleteWithRegisteredCommand(_commands.Select(c => c.Name).ToList());

            while (true)
            {
                //string command = _screenManager.GetCommand();
                string command = ReadLine.Read("aelf> ");


                if (string.IsNullOrWhiteSpace(command))
                {
                    continue;
                }

                ReadLine.AddHistory(command);

                // stop the repl if "quit", "Quit", "QuiT", ... is encountered
                if (command.Equals(ExitReplCommand, StringComparison.OrdinalIgnoreCase))
                {
                    Stop();
                    break;
                }

                if (command.StartsWith("sub events"))
                {
                    string[] splitOnSpaces = command.Split(' ');

                    if (splitOnSpaces.Length == 3)
                    {
                        EventMonitor mon = new EventMonitor(_port, splitOnSpaces[2]);
                        mon.Start().GetResult();
                        Console.ReadKey();
                    }
                    else
                    {
                        Console.WriteLine("Sub events - incorrect arguments");
                    }
                }

                CmdParseResult       parsedCmd = _cmdParser.Parse(command);
                CliCommandDefinition def       = GetCommandDefinition(parsedCmd.Command);

                if (def == null)
                {
                    _screenManager.PrintCommandNotFound(command);
                }
                else
                {
                    ProcessCommand(parsedCmd, def);
                }
            }
        }
Beispiel #10
0
        private static void ReadLineConfiguration()
        {
            ReadLine.HistoryEnabled = true;
            var app             = new CommandLineApplication <RootCommand>();
            var initialCommands = ArgumentExecutor(app, new string[] { "--version" });

            ReadLine.AutoCompletionHandler = new AutoCompletionHandler(initialCommands.ToArray());
            ReadLine.AddHistory(initialCommands.ToArray());
        }
Beispiel #11
0
        public static string Read(string prompt)
        {
            string input = ReadLine.Read(prompt);

            if (input.Trim().Length > 0)
            {
                ReadLine.AddHistory(input);
            }
            return(input);
        }
Beispiel #12
0
        public static string RedPeanutCLI()
        {
            PrintCLI();
            string input = ReadLine.Read();

            if (input.Trim().Length > 0)
            {
                ReadLine.AddHistory(input);
            }

            return(input.TrimEnd(' '));
        }
        private static void LoadHistory()
        {
            var file = GetHistoryFile();

            if (!File.Exists(file))
            {
                File.WriteAllLines(file, new string[] { });
            }

            ReadLine.HistoryEnabled = true;
            ReadLine.AddHistory(File.ReadAllLines(file));
        }
Beispiel #14
0
        private static void SaveHistory()
        {
            if (ReadLine.HistoryEnabled)
            {
                //remove empty line
                var data = ReadLine.GetHistory().Where(a => !string.IsNullOrWhiteSpace(a));
                ReadLine.ClearHistory();
                ReadLine.AddHistory(data.ToArray());

                File.WriteAllLines(GetHistoryFile(), data.Skip(Math.Max(0, data.Count() - 100)));
            }
        }
        private void LoadHistory()
        {
            if (!File.Exists(HistoryFilePath))
            {
                return;
            }

            var lines = File.ReadLines(HistoryFilePath, HistoryFileEncoding)
                        .TakeLast(HistoryMax)
                        .ToArray();

            ReadLine.AddHistory(lines);
        }
Beispiel #16
0
 private static void HandleKey(ConsoleKeyInfo keyInfo)
 {
     if (keyInfo.Key != ConsoleKey.Enter)
     {
         handler.Handle(keyInfo);
     }
     else
     {
         CLIOutput.WriteLine();
         CLI.HandleQuery(handler.Text);
         ReadLine.AddHistory(handler.Text);
         CreateHandler();
     }
 }
Beispiel #17
0
        public async System.Threading.Tasks.Task InputLoop()
        {
            string input = null;

            txtOut.WriteLine("Syntax: Origin-Destination outDate [inDate]");
            while (!nameof(Commands.Quit).Equals(input, StringComparison.OrdinalIgnoreCase))
            {
                input = ReadLine.Read("FS> ");
                if (input != "")
                {
                    ReadLine.AddHistory(input);
                    await Run(input);
                }
            }
        }
Beispiel #18
0
 private static async Task Execute()
 {
     try
     {
         Console.WriteLine();
         Console.WriteLine("======================================================");
         Console.WriteLine("Enter code and press [ENTER]");
         string codeText = ReadLine.Read("bytecode> ");
         ReadLine.AddHistory(codeText);
         await ExecuteCode(codeText);
     }
     catch (Exception e)
     {
         WriteError(e.Message);
     }
 }
Beispiel #19
0
 public string Prompt(string prompt, bool mustProvide = true, bool keepHistory = true)
 {
     while (true)
     {
         var value = ReadLine.Read(prompt + "> ");
         if (string.IsNullOrEmpty(value) && mustProvide)
         {
             continue;
         }
         if (keepHistory)
         {
             ReadLine.AddHistory(value);
         }
         return(value);
     }
 }
Beispiel #20
0
        public static void Main(string[] args)
        {
            Console.WriteLine("ReadLine Library Demo");
            Console.WriteLine("---------------------");
            Console.WriteLine();

            string[] history = new string[] { "ls -a", "dotnet run", "git init" };
            ReadLine.AddHistory(history);

            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            string input = ReadLine.Read("(prompt)> ");

            Console.WriteLine(input);

            input = ReadLine.ReadPassword("Enter Password> ");
            Console.WriteLine(input);
        }
Beispiel #21
0
        public static string RedPeanutCLI(IAgentInstance agent)
        {
            PrintCLI(agent);
            string          input = ReadLine.Read();
            StandardCommand cmd   = new StandardCommand(agent);

            if (cmd.Execute(input))
            {
                input = "";
            }

            if (input.Trim().Length > 0)
            {
                ReadLine.AddHistory(input);
            }

            return(input);
        }
Beispiel #22
0
        /// <summary>
        /// Load Command Text History
        /// </summary>
        public static void Load(IPromptConfiguration config)
        {
            var historyFile = config.GetOption("HistoryFile");

            if (string.IsNullOrEmpty(historyFile))
            {
                return;
            }


            ReadLine.HistoryEnabled = true;
            if (!File.Exists(historyFile))
            {
                return;
            }
            var history = File.ReadAllLines(historyFile);

            ReadLine.AddHistory(history);
        }
Beispiel #23
0
        public static void Main(string[] args)
        {
            Console.WriteLine("ReadLine Library Demo");
            Console.WriteLine("---------------------");
            Console.WriteLine();

            string[] history = new string[] { "ls -a", "dotnet run", "git init" };
            ReadLine.AddHistory(history);

            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            string input = ReadLine.Read("(prompt)> ");

            Console.WriteLine(input);

            input = ReadLine.ReadPassword("Enter Password> ");
            Console.WriteLine(input);

            System.Threading.Tasks.Task.Run(() => {
                var a = ReadLine.Read("From Task >");
                Console.WriteLine(a);
            });
            System.Threading.Thread.Sleep(1000);
            ReadLine.Send(new ConsoleKeyInfo('\n', ConsoleKey.Enter, false, false, false));

            System.Threading.Tasks.Task.Run(() => {
                var a = ReadLine.Read("From Task >");
                Console.WriteLine(a);
            });
            System.Threading.Thread.Sleep(1000);
            ReadLine.Send("This is a slow string being typed\n", 500);
            System.Threading.Tasks.Task.Run(() => {
                var a = ReadLine.Read("From Task >");
                Console.WriteLine(a);
            });
            System.Threading.Thread.Sleep(1000);
            ReadLine.Send(ConsoleKey.UpArrow);
            //ReadLine.Send();

            Console.ReadKey(true);
        }
Beispiel #24
0
        public void RunInteractive()
        {
            ReadLine.AutoCompletionHandler = this;

            while (!_context.ShouldExit)
            {
                Console.WriteLine();

                var currentFolderPath = _context.CurrentFolder.GetFullPath();
                var statement         = ReadLine.Read($"{currentFolderPath}> ").Trim();

                if (statement.Length == 0)
                {
                    continue;
                }

                ReadLine.AddHistory(statement);

                ExecuteStatemenet(statement);
            }
        }
Beispiel #25
0
        public string ReadPrompt()
        {
            PrintPrompt();

            string str;

            try
            {
                str = ReadLine.Read();
            }
            catch (Exception)
            {
                return(null);
            }

            if (!string.IsNullOrWhiteSpace(str))
            {
                ReadLine.AddHistory(str);
            }

            return(str);
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            // Command window on Windows has ANSI disabled by default
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                ConsoleUtils.EnableANSI();
            }

            PrintWelcomeMessage();

            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                string command = ReadLine.Read(Prompt);
                if (command.StartsWith("/") && Commands.TryGetValue(command.Substring(1), out var cmd))
                {
                    cmd.Item2();
                }
                else
                {
                    ReadLine.AddHistory(command);
                    var result = scripting.Eval(command);
                    if (result.Result != null)
                    {
                        Console.WriteLine();
                        if (result.Status == ScriptingExecutionStatus.Error)
                        {
                            Console.WriteLine(AnsiUtils.Color(result.Result, AnsiColor.Red));
                        }
                        else
                        {
                            Console.WriteLine(AnsiUtils.Color(result.Result, AnsiColor.Green));
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
        public void Init()
        {
            try
            {
                _cliConsole.WriteInteresting($"Loading history file from {Path.Combine(AppDomain.CurrentDomain.BaseDirectory, HistoryFilePath)}" + Environment.NewLine);

                if (File.Exists(HistoryFilePath))
                {
                    foreach (string line in File.ReadLines(HistoryFilePath).Distinct().TakeLast(60))
                    {
                        if (line != _removedString)
                        {
                            ReadLine.AddHistory(line);
                            _historyCloned.Insert(0, line);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _cliConsole.WriteErrorLine($"Could not load cmd history from {HistoryFilePath} {e.Message}");
            }
        }
        public void UpdateHistory(string statement)
        {
            if (!File.Exists(HistoryFilePath))
            {
                File.Create(HistoryFilePath).Dispose();
            }

            if (!SecuredCommands.Any(statement.Contains))
            {
                List <string> history = ReadLine.GetHistory();
                if (history.LastOrDefault() != statement)
                {
                    ReadLine.AddHistory(statement);
                    _historyCloned.Insert(0, statement);
                }
            }
            else
            {
                ReadLine.AddHistory(_removedString);
                _historyCloned.Insert(0, statement);
            }

            File.WriteAllLines(HistoryFilePath, _historyCloned.Distinct().Reverse().ToArray());
        }
Beispiel #29
0
        private static void RunEvalLoop()
        {
            try
            {
                if (File.Exists(HistoryFilePath))
                {
                    foreach (string line in File.ReadLines(HistoryFilePath).TakeLast(60))
                    {
                        if (line != _removedString)
                        {
                            ReadLine.AddHistory(line);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                CliConsole.WriteErrorLine($"Could not load cmd history from {HistoryFilePath} {e.Message}");
            }

            ReadLine.AutoCompletionHandler = new AutoCompletionHandler();

            while (true)
            {
                try
                {
                    if (_terminal != Terminal.Cmder)
                    {
                        Console.ForegroundColor = ColorScheme.Text;
                    }
                    int    bufferSize = 1024 * 16;
                    string statement;
                    using (Stream inStream = System.Console.OpenStandardInput(bufferSize))
                    {
                        Console.SetIn(new StreamReader(inStream, Console.InputEncoding, false, bufferSize));
                        CliConsole.WriteLessImportant("nethermind> ");
                        statement = _terminal == Terminal.Cygwin ? Console.ReadLine() : ReadLine.Read();
                        CleanStatement(statement);

                        if (!File.Exists(HistoryFilePath))
                        {
                            File.Create(HistoryFilePath).Dispose();
                        }

                        if (!SecuredCommands.Any(sc => statement.Contains(sc)))
                        {
                            ReadLine.AddHistory(statement);

                            using (var fileStream = File.AppendText(HistoryFilePath))
                            {
                                fileStream.WriteLine(statement);
                            }
                        }
                        else
                        {
                            ReadLine.AddHistory(_removedString);
                        }
                    }

                    if (statement == "exit")
                    {
                        break;
                    }

                    JsValue result = _engine.Execute(statement);
                    if (result.IsObject() && result.AsObject().Class == "Function")
                    {
                        CliConsole.WriteGood(result.ToString());
                        CliConsole.WriteLine();
                    }
                    else if (!result.IsNull())
                    {
                        string text = Serializer.Serialize(result.ToObject(), true);
//                        File.AppendAllText("C:\\temp\\cli.txt", text);
                        CliConsole.WriteGood(text);
                    }
                    else
                    {
                        CliConsole.WriteLessImportant("null");
                        CliConsole.WriteLine();
                    }

//                    bool isNull = result.IsNull();
//                    if (!isNull)
//                    {
//                        CliConsole.WriteString(result);
//                    }
                }
                catch (Exception e)
                {
                    CliConsole.WriteException(e);
                }
            }
        }
Beispiel #30
0
        public void Run()
        {
            ReadLine.AutoCompletionHandler = this;

            var argumentParser = new ArgumentParser();

            while (!_context.ShouldExit)
            {
                Console.WriteLine();

                var line = ReadLine.Read("> ").Trim();

                if (line.Length == 0)
                {
                    line = ReadLine.GetHistory().LastOrDefault();

                    if (line == null)
                    {
                        continue;
                    }
                }
                else
                {
                    ReadLine.AddHistory(line);
                }

                string[] args;

                try
                {
                    args = argumentParser.Parse(line).ToArray();
                }
                catch (ArgumentParser.UnclosedQuotationMarkException)
                {
                    using (new ColoredConsole(ConsoleColor.Red))
                        Console.WriteLine("Unclosed quotation mark.");

                    continue;
                }

                var command = FindCommand(args[0]);

                if (command == null)
                {
                    using (new ColoredConsole(ConsoleColor.Red))
                        Console.WriteLine("Invalid command.");

                    continue;
                }

                try
                {
                    command.Execute(args.Skip(1).ToArray(), _context);
                }
                catch (CommandException exception)
                {
                    ConsoleHelper.PrintError(exception.Message);
                }
                catch (JournalException exception)
                {
                    ConsoleHelper.PrintError(exception.Message);
                }
                catch (ValidationException exception)
                {
                    ConsoleHelper.PrintError(exception.Message);
                }
            }
        }