/// <summary>
        /// Gets suggestions for the command line
        /// </summary>
        /// <param name="text">Console strings typed to get suggestions</param>
        /// <param name="index"></param>
        /// <returns>String array of matches</returns>
        public string[] GetSuggestions(string text, int index)
        {
            var sug = new List <string>();

            try
            {
                sug.AddRange(new List <string> {
                    "quit", "--help"
                });
                //Automatically and conveniently updates list with history
                sug.AddRange(ReadLine.GetHistory().ToImmutableHashSet().ToList());

                // NOTE: Add string collections to return suggestions.
                if (_additionalSeedStrings != null)
                {
                    sug.AddRange(_additionalSeedStrings);
                }

                return(sug.ToArray().Where(x => x.StartsWith(text)).ToArray());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(sug.ToArray());
        }
Esempio n. 2
0
        public void TestGetCorrectHistory()
        {
            var history = ReadLine.GetHistory();

            Assert.Equal(3, history.Count);
            Assert.Equal("git init", history.Last());
        }
Esempio n. 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}");
                }
            }
        }
 private static void SaveHistory()
 {
     if (ReadLine.HistoryEnabled)
     {
         var data = ReadLine.GetHistory().Where(a => !string.IsNullOrWhiteSpace(a));
         File.WriteAllLines(GetHistoryFile(), data.Skip(Math.Max(0, data.Count() - 100)));
     }
 }
Esempio n. 5
0
        public override Task <bool> Handle(ConsoleCommandEvent <HistoryConsoleCommand> request, CancellationToken cancellationToken)
        {
            foreach (var item in ReadLine.GetHistory().Distinct())
            {
                Console.WriteLine(item, Color.Gray);
            }

            return(Task.FromResult(true));
        }
Esempio n. 6
0
        /// <summary>
        /// Runs the command after instantiation
        /// </summary>
        public void Run()
        {
            Console.WriteLine($"Command history");
            foreach (var historyItem in ReadLine.GetHistory().ToImmutableSortedSet())
            {
                Console.WriteLine(historyItem);
            }

            ReadLine.GetHistory();
        }
Esempio n. 7
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 SaveHistory()
        {
            var lines = ReadLine.GetHistory()
                        .TakeLast(HistoryMax)
                        .ToArray();

            using var sw = File.CreateText(HistoryFilePath);

            foreach (var line in lines)
            {
                sw.WriteLine(line);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Saves Command Text History
        /// </summary>
        public static void Save(IPromptConfiguration config)
        {
            var historyFile = config.GetOption("HistoryFile");

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

            var history = ReadLine.GetHistory();

            history = history.Distinct().ToList(); // Remove duplicates
            File.WriteAllLines(historyFile, history);
        }
Esempio n. 10
0
        private static void CmdHistory(TextWriter output,
                                       CommandLineApplication app,
                                       bool onlyResult)
        {
            app.Command("history", cmd =>
            {
                cmd.Description = "Show history command";
                cmd.AddName("h");

                var optEnabled = cmd.OptionEnum("--enabled|-e", "Enabled/Disable history", "0", "1");

                cmd.OnExecute(() =>
                {
                    if (optEnabled.HasValue())
                    {
                        ReadLine.HistoryEnabled = optEnabled.Value() == "1";
                        if (ReadLine.HistoryEnabled)
                        {
                            LoadHistory();
                        }
                        else
                        {
                            ReadLine.ClearHistory();
                        }
                    }
                    else
                    {
                        if (!ReadLine.HistoryEnabled)
                        {
                            if (!onlyResult)
                            {
                                output.WriteLine("History disabled!");
                            }
                        }
                        else
                        {
                            var lineNum = 0;
                            foreach (var item in ReadLine.GetHistory())
                            {
                                output.WriteLine($"{lineNum} {item}");
                                lineNum++;
                            }
                        }
                    }
                });
            });
        }
Esempio n. 11
0
        private void SaveHistory()
        {
            // save history for later use
            var directory = Path.Combine(Path.GetTempPath(), "naos_console");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            using (var writer = new StreamWriter(
                       File.Create(Path.Combine(directory, "history.db"))))
            {
                Console.WriteLine("saving history", Color.Gray);
                foreach (var history in ReadLine.GetHistory().Distinct())
                {
                    if (!history.IsNullOrEmpty() && !history.EqualsAny(new[] { "exit" }))
                    {
                        writer.WriteLine(history);
                    }
                }
            }
        }
        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());
        }
        public static async Task <int> Main(string[] args)
        {
            initialArgs = args;

            // create a di container
            var services = new ServiceCollection();

            // register services
            services.RegisterServices(HandleNoProfiles);

            // register commands
            services.RegisterCommands();

            // register readline helper
            services.RegisterReadLine();

            // build service provider
            var sp = services.BuildServiceProvider();

            var app = new CliApplicationBuilder()
                      .AddCommandsFromThisAssembly()
                      .UseTypeActivator(sp.GetService)
                      .Build();

            // handle interactive cli
            if (args == null || args.Length == 0)
            {
                var commandParsingService = sp.GetRequiredService <ICommandParsingService>();
                var commandText           = string.Empty;

                while (!commandText.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
                {
                    Console.Write("> ");
                    commandText = string.Empty;
                    while (string.IsNullOrWhiteSpace(commandText))
                    {
                        commandText = ReadLine.Read(string.Empty, string.Empty).Trim();
                    }

                    if (commandText.Equals("clear", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Console.Clear();
                        continue;
                    }

                    if (commandText.Equals("history", StringComparison.InvariantCultureIgnoreCase))
                    {
                        foreach (var history in ReadLine.GetHistory().ToArray().Reverse().Take(10))
                        {
                            Console.WriteLine(history);
                        }

                        continue;
                    }

                    if (commandText.Equals("exit", StringComparison.InvariantCultureIgnoreCase))
                    {
                        continue;
                    }

                    var parsedArguments = commandParsingService.ParseCommandString(commandText);

                    await app.RunAsync(parsedArguments);
                }

                Environment.Exit((int)ExitCodesEnum.Normal);
            }

            // handle passed in arguments
            return(await app.RunAsync(args));
        }
Esempio n. 14
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);
                }
            }
        }
Esempio n. 15
0
 private static void CurrentDomainOnProcessExit(object sender, EventArgs e)
 {
     File.WriteAllLines(HistoryFilePath, ReadLine.GetHistory().TakeLast(60));
 }
Esempio n. 16
0
        public static void Main(string[] args)
        {
            // args = new[] {"/Users/cn/a3/c308/client/Unity/Tools/excel/lua/app/CollectImg2Excel.lua"};

            // // no use
            // AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs eventArgs)
            // {
            //     string assemblyFile = (eventArgs.Name.Contains(','))
            //         ? eventArgs.Name.Substring(0, eventArgs.Name.IndexOf(','))
            //         : eventArgs.Name;
            //
            //     assemblyFile += ".dll";
            //
            //     // // Forbid non handled dll's
            //     // if (!LOAD_ASSEMBLIES.Contains(assemblyFile))
            //     // {
            //     //     return null;
            //     // }
            //
            //     string absoluteFolder = new FileInfo((new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).LocalPath).Directory.FullName;
            //     string targetPath = Path.Combine(absoluteFolder, assemblyFile);
            //
            //     try
            //     {
            //         Console.WriteLine($"try load:{targetPath}");
            //         return Assembly.LoadFile(targetPath);
            //     }
            //     catch (Exception)
            //     {
            //         return null;
            //     }
            //     Console.WriteLine($"load:{targetPath}");
            // };


            // // no use 2
            // var PrivateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath + (System.IO.Path.PathSeparator+AppDomain.CurrentDomain.BaseDirectory+"lib");
            // AppDomain.CurrentDomain.SetupInformation.PrivateBinPath = PrivateBinPath;
            // Console.WriteLine($"PathSeparator:{System.IO.Path.PathSeparator}\nPrivateBinPath:{PrivateBinPath}=>{AppDomain.CurrentDomain.SetupInformation.PrivateBinPath}\nBaseDirectory:{AppDomain.CurrentDomain.BaseDirectory} ");


            // for (int i = 0; i < args.Length; i++)
            // {
            //     Debug.WriteLine("args{0}: {1}", i, args[i]);
            // }

            // var w = AppDomain.CurrentDomain.GetAssemblies();
            // var asm = Assembly.LoadFrom("");
            // asm.GetExportedTypes();

            // Activator.CreateInstance(typeof(String));

            // var l = LuaCallCSharpTypes.L;

            // var size = NPOI.SS.Util.ImageUtils.GetImageDimension(null);
            // var wb = new XSSFWorkbook();
            // var sheet = wb.GetSheet("");
            // var picInd = wb.AddPicture(new FileStream("", FileMode.Open), 6);
            // var helper = wb.GetCreationHelper();
            // var drawing = sheet.CreateDrawingPatriarch();
            // var anchor = helper.CreateClientAnchor();
            // anchor.Col1 = 0;
            // anchor.Col2 = 0;
            // anchor.Row1 = 5;
            // var pict = drawing.CreatePicture(anchor, picInd);
            // pict.Resize();


            LuaEnv luaenv = LuaEnvSingleton.Instance;
            var    L      = luaenv.L;

            if (0 == LuaAPI.xlua_getglobal(L, "_VERSION"))
            {
                Console.WriteLine($"{LuaAPI.lua_tostring(L, -1)}");
            }

            ExecutableDir = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/");// Application.ExecutablePath.Replace(Path.GetFileName(Application.ExecutablePath), "");

            luaenv.DoString("package.cpath = package.cpath .. ';./lib?.dylib;./?.dylib';"
                            + string.Format("package.cpath = package.cpath .. ';{0}lib?.dylib;{0}lib/lib?.dylib;{0}lib/?.dylib;{0}../lib/lib?.dylib;{0}../lib/?.dylib'", ExecutableDir)
                            );

            var initlua = ExecutableDir + "init.lua";

            if (File.Exists(initlua))
            {
                luaenv.DoFile(initlua);
            }

            var mainlua = ExecutableDir + "lua/main.lua";

            if (args.Length > 0)
            {
                mainlua = args[0];
                var maindir = mainlua.Substring(0, mainlua.LastIndexOf("/"));
                luaenv.DoString(string.Format("package.path = package.path .. ';{0}/../?.lua;{0}/?.lua;{0}/lua/?.lua;'", maindir)
                                + @"package.path = package.path .. ';lua/?.lua' .. ';../lua/?.lua';"
                                + string.Format("package.path = package.path .. ';{0}/?.lua;;{0}/lua/?.lua;'", ExecutableDir));

                LuaTable env = luaenv.NewTable();
                env.Set("__index", luaenv.Global);
                env.Set("__newindex", luaenv.Global);

                LuaTable argv = luaenv.NewTable();
                for (int i = 0; i < args.Length; ++i)
                {
                    // Debug.WriteLine($"cs-argv[{i}] = {args[i]}");
                    argv.Set(i, args[i]);
                }
                env.Set("argv", argv);
                env.SetMetaTable(env);

                if (File.Exists(mainlua))
                {
                    luaenv.DoFile(mainlua, env);
                }
            }
            else
            {
                luaenv.DoString(@"package.path = package.path .. ';lua/?.lua' .. ';../lua/?.lua';"
                                + string.Format("package.path = package.path .. ';{0}/?.lua;;{0}/lua/?.lua;'", ExecutableDir));
                // Debug.WriteLine("run default entry lua/main.lua");
                Debug.WriteLine(" usage:\n\tosx/unix: mono xlua.exe path/to/entry.lua");
                Debug.WriteLine("\twindows: xlua.exe path/to/entry.lua");
                Debug.WriteLine("Or type lua code in Interaction Mode\nGood luck.");
                Console.Write("xlua");


                // // XLua.LuaDLL.Lua.lua_pushcclosure(L, (IntPtr)(pmain), 0);
                // XLua.LuaDLL.Lua.xlua_pushinteger(L, args.Length - 1);
                // luaenv.Translator.PushAny(L, args);
                // var ok = pmain(L);
                // Console.WriteLine($"lua return: {ok}");


                // LuaDoREPL(L);
                //
                // return;
                //*
                var fhistory = "xlua.history.lua";
                System.ReadLine.HistoryEnabled = false;
                var historyList = ReadLine.GetHistory();
                if (File.Exists(fhistory))
                {
                    historyList.AddRange(File.ReadAllLines(fhistory)
                                         .GroupBy(i => i)
                                         .Select(i => i.First()));
                    // ReadLine.AddHistory(historyList.ToArray());
                }

                var history    = File.AppendText(fhistory);
                int historyIdx = 0;
                var cmd        = "";
                while (cmd != "quit" && cmd != "exit")
                {
                    cmd = cmd.Trim().Replace("\0", "");
                    if (!historyList.Contains(cmd))
                    {
                        history.WriteLine(cmd);
                        history.Flush();
                    }
                    if (cmd.Length > 0)
                    {
                        historyList.Add(cmd);
                    }
                    if (cmd == "cls")
                    {
                        Console.Clear();
                        goto next;
                    }
                    if (cmd != ""
                        // && !cmd.Contains(" ")
                        && !cmd.Contains("=") &&
                        !cmd.Contains("print")
                        )
                    {
                        if (!cmd.Contains(",") &&
                            !cmd.Contains(" ")
                            )
                        {
                            cmd = "return  tostring(" + cmd + ")";
                        }
                        else
                        {
                            cmd = "return " + cmd;
                        }
                    }

                    try
                    {
                        if (cmd.Length > 0)
                        {
                            try
                            {
                                var ret = luaenv.DoString(cmd);
                                if (ret != null && ret.Length > 0)
                                {
                                    foreach (var o in ret)
                                    {
                                        // ObjectTranslatorPool.Instance.Find(L).PushAny(L, o);
                                        // var v = o is null ? XLua.LuaDLL.Lua.lua_tostring(L, -1) : o.ToString();
                                        var v = o is null ? "nil or native_ptr try tostring(obj) again" : o.ToString();
                                        Console.Write("{0}\t", v);
                                    }

                                    Console.Write("\n");
                                }
                            }
                            catch (LuaException e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }
                    }
                    catch (LuaException e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message + "\n#trace: \n" + e.StackTrace);
                    }

next:
                    cmd = ReadLine.Read("> ");
                }// while
                history.Close();
                Console.WriteLine("\nexit no error.");
                // */
            }
        }
Esempio n. 17
0
 public void TestUpdatesHistory()
 {
     ReadLine.AddHistory("mkdir");
     Assert.Equal(4, ReadLine.GetHistory().Count);
 }
Esempio n. 18
0
 public void TestNoInitialHistory()
 {
     Assert.Equal(3, ReadLine.GetHistory().Count);
 }