public static void Main(string[] args) { var le = new LineEditor("foo") { HeuristicsMode = "csharp" }; le.AutoCompleteEvent += (text, pos) => { var completions = new [] { "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" }; return(new LineEditor.Completion(string.Empty, completions)); }; string s; while ((s = le.Edit("shell> ", "")) != null) { Console.WriteLine("----> [{0}]", s); } }
public static void Main(string[] args) { LineEditor lineEditor = new LineEditor("DiceShell"); string input; while ((input = lineEditor.Edit("DiceShell $ ", "")) != null) { if (string.IsNullOrEmpty(input)) { continue; } try { AntlrInputStream inputStream = new AntlrInputStream(input); DiceLexer diceLexer = new DiceLexer(inputStream); CommonTokenStream commonTokenStream = new CommonTokenStream(diceLexer); DiceParser diceParser = new DiceParser(commonTokenStream); DiceParser.ShellContext context = diceParser.shell(); DiceVisitor visitor = new DiceVisitor(); int result = (int)visitor.Visit(context); Console.WriteLine(string.Format("[{0:HH:mm:ss}] {1}\n", DateTime.Now, result)); } catch (Exception) { Console.WriteLine("Parsing Error\n"); } } }
// workaround as long as getline.cs might care about history on unix protected virtual string ReadLine(bool addToHistory) { if (!InteractiveIO) { ThrowNotInteractiveException(); } return(UseUnixLikeInput ? _getlineEditor.Edit("", "", addToHistory) : Console.ReadLine()); }
// workaround as long as getline.cs might care about history on unix internal virtual string ReadLine(bool addToHistory, string intialValue = "") { if (!InteractiveIO) { ThrowNotInteractiveException(); } return(UseUnixLikeInput ? _getlineEditor.Edit("", intialValue, addToHistory) : Console.ReadLine()); }
static public string ConsoleEditString(this string Default, string Prefix = null) { var Editor = new LineEditor(null); Editor.TabAtStartCompletes = true; return(Editor.Edit(Prefix ?? "", Default)); }
static public string ConsoleEditString(this string @default, string prefix = null) { var editor = new LineEditor(null); editor.TabAtStartCompletes = true; return(editor.Edit(prefix ?? "", @default)); }
public void Run() { LineEditor le = new LineEditor("foo"); // Prompts the user for input while (true) { string s = le.Edit("# ", ""); Exec(s).Wait(); } }
public void StartLineEditor() { LineEditor le = new LineEditor("LineEditor", 50); le.AutoCompleteEvent = (string text, int pos) => { //text = text.ToLower(); string token = null; for (int i = pos - 1; i >= 0; i--) { if (Char.IsWhiteSpace(text[i])) { token = text.Substring(i + 1, pos - i - 1); break; } else if (i == 0) { token = text.Substring(0, pos); } } List <string> results = new List <string>(); if (token == null) { token = string.Empty; results.AddRange(CommandMatcher.AutoComplete.Select(x => x.Path).ToArray()); } else { string[] completePaths = CommandMatcher.AutoComplete .Where(x => x.Path.Length > pos) .Select(x => x.Path.Substring(pos - token.Length)) .ToArray(); for (int i = 0; i < completePaths.Length; i++) { if (completePaths[i].StartsWith(token)) { string result = completePaths[i]; results.Add(result.Substring(token.Length, result.Length - token.Length)); } } } return(new LineEditor.Completion(token, results.ToArray())); }; string s; while ((s = le.Edit("> ", "")) != null) { if (new[] { "exit", "quit", "bye", "q", "e" }.Contains(s)) { break; } CommandMatcher.CallAction(s); } }
public string Edit(string prompt) { if (lineEditor != null) { return(lineEditor.Edit(prompt, null)); } beforeRenderPrompt?.Invoke(); System.Console.Write(prompt); afterRenderPrompt?.Invoke(); return(System.Console.ReadLine()); }
public void Run() { LineEditor le = new LineEditor("foo") { HeuristicsMode = "csharp" }; // Prompts the user for input while (true) { string s = le.Edit("# ", ""); Exec(s).Wait(); } }
/// <summary> /// Static method to present a prompt in a REPL. /// </summary> /// <param name="prompt"></param> /// <returns></returns> public static string LineReader(string prompt) { if (Mode == ModeEnum.Terminal) { if (_lineEditor == null) { _lineEditor = new LineEditor("OpenLisp.NET"); } return(_lineEditor.Edit(prompt, "")); } Console.WriteLine(prompt); Console.Out.Flush(); return(Console.ReadLine()); }
public static string Readline(string prompt) { if (mode == Mode.Terminal) { if (lineedit == null) { lineedit = new LineEditor("Mal"); } return(lineedit.Edit(prompt, "")); } else { Console.Write(prompt); Console.Out.Flush(); return(Console.ReadLine()); } }
/// <summary> /// Method implements main application loop where application search configuration files, load them and /// then run LineEditor (emulator of Unix line terminal). /// </summary> private void Loop() { PreloadConfiguration(); String command; LineEditor = new LineEditor(null); LineEditor.AutoCompleteEvent += OnAutoComplete; LineEditor.TabKeyEvent += OnEditorTabKeyEvent; InvokeOnConfigurationLoaded(EventArgs.Empty); while ((command = LineEditor.Edit(CurrentSession.Prompt, "")) != null) { RunCommand(command); } }
public static void Main(string[] args) { PrintIntroduction(); LineEditor editor = new LineEditor("Bing Dictionary"); var dic = new BingDictionary(); var sounder = new Sounder(); QueryResult LastQuery = null; while (true) { string line = editor.Edit("> ", string.Empty); if (line == null) { break; } else { line = line.Trim(); if (line.Length == 0) { continue; } else if (line == "-q") { break; } else if (line == "-a" || line == "-b") { if (LastQuery != null) { sounder.PronounceWord(line, LastQuery); } else { Console.WriteLine("No query history."); } } else { LastQuery = dic.SearchWord(line); } } } }
static void Main(string[] args) { // Creates a line editor, and sets the name of the editing session to // "foo". This is used to save the history of input entered LineEditor le = new LineEditor("foo") { HeuristicsMode = "csharp" }; // Configures auto-completion, in this example, the result // is always to offer the numbers as completions le.AutoCompleteEvent += delegate(string text, int pos) { string prefix = ""; var completions = new string[] { "first", "reduce", "map" }; return(new Mono.Terminal.LineEditor.Completion(prefix, completions)); }; string s; // Prompts the user for input while ((s = le.Edit("> ", "")) != null) { if (s == "exit") { System.Environment.Exit(0); } var compiler = new Lisp.Compiler.Compiler(); try { if (s != string.Empty) { Console.WriteLine(compiler.Compile(s).Invoke().Stringify(true)); } } catch (Exception e) { Console.WriteLine(e); } } }
public void Run() { var le = new LineEditor( Config.ConsoleMode.AppName, Config.ConsoleMode.HistorySize.GetValueOrDefault(10)) { AutoCompleteEvent = (text, pos) => GetEntries(text) }; using (CommandsOptions.HideCommandOfType <ConsoleCommand>()) { Writer.WriteLines( "Type ctrl+c to exit.", "Type \"cls\" to clear the console window.", "Type \"> filename\" to redirect output to a file."); do { string[] args; do { args = le.Edit(Config.ConsoleMode.CommandPromptText + "> ", string.Empty).SplitCmdLineArgs(); } while (args.IsNullOrEmpty()); if (args[0].Equals("cls", StringComparison.OrdinalIgnoreCase)) { Console.Clear(); } else if (args[0].Equals(CommandName, StringComparison.OrdinalIgnoreCase)) { //already in console mode } else { le.SaveHistory(); RunCommand(args); } } while (true); } }
private static async Task MainAsync(string[] args, CancellationToken cancel) { #region Options Parsing... string clusterFile = null; var dbName = "DB"; var partition = new string[0]; bool showHelp = false; int timeout = 30; int maxRetries = 10; string execCommand = null; var opts = new OptionSet() { { "c|connfile=", "The path of a file containing the connection string for the FoundationDB cluster.", v => clusterFile = v }, { "p|partition=", "The name of the database partition to open.", v => partition = v.Trim().Split('/') }, { "t|timeout=", "Default timeout (in seconds) for failed transactions.", (int v) => timeout = v }, { "r|retries=", "Default max retry count for failed transactions.", (int v) => maxRetries = v }, { "exec=", "Execute this command, and exits immediately.", v => execCommand = v }, { "h|help", "Show this help and exit.", v => showHelp = v != null } }; var extra = opts.Parse(args); if (showHelp) { //TODO! opts.WriteOptionDescriptions(Console.Out); return; } string startCommand = null; if (!string.IsNullOrEmpty(execCommand)) { startCommand = execCommand; } else if (extra.Count > 0) { // the remainder of the command line will be the first command to execute startCommand = String.Join(" ", extra); } #endregion bool stop = false; Db = null; try { Db = await ChangeDatabase(clusterFile, dbName, partition, cancel); Db.DefaultTimeout = Math.Max(0, timeout) * 1000; Db.DefaultRetryLimit = Math.Max(0, maxRetries); Console.WriteLine("Using API v" + Fdb.ApiVersion + " (max " + Fdb.GetMaxApiVersion() + ")"); Console.WriteLine("Cluster file: " + (clusterFile ?? "<default>")); Console.WriteLine(); Console.WriteLine("FoundationDB Shell menu:"); Console.WriteLine("\tdir\tShow the content of the current directory"); Console.WriteLine("\ttree\tShow all the directories under the current directory"); Console.WriteLine("\tsampling\tDisplay statistics on random shards from the database"); Console.WriteLine("\tcoordinators\tShow the current coordinators for the cluster"); Console.WriteLine("\tmem\tShow memory usage statistics"); Console.WriteLine("\tgc\tTrigger garbage collection"); Console.WriteLine("\tquit\tQuit"); Console.WriteLine("Ready..."); var le = new LineEditor("FDBShell"); string[] cmds = new string[] { "cd", "coordinators", "count", "dir", "exit", "gc", "help", "layer", "map", "mem", "mkdir", "mv", "partition", "pwd", "quit", "ren", "rmdir", "sampling", "shards", "show", "status", "topology", "tree", "version", "wide", }; le.AutoCompleteEvent = (txt, pos) => { string[] res; int p = txt.IndexOf(' '); if (p > 0) { string cmd = txt.Substring(0, p); string arg = txt.Substring(p + 1); if (cmd == "cd") { // handle completion for directories // txt: "cd foo" => prefix = "foo" // txt: "cd foobar/b" => prefix = "b" string path = CurrentDirectoryPath; string prefix = ""; string search = arg; p = arg.LastIndexOf('/'); if (p > 0) { path = Path.Combine(path, arg.Substring(0, p)); search = arg.Substring(p + 1); prefix = arg.Substring(0, p + 1); } var subdirs = RunAsyncCommand((db, log, ct) => AutoCompleteDirectories(path, db, log, ct), cancel).GetAwaiter().GetResult(); if (!subdirs.HasValue || subdirs.Value == null) { return(new LineEditor.Completion(txt, null)); } res = subdirs.Value .Where(s => s.StartsWith(search, StringComparison.Ordinal)) .Select(s => (cmd + " " + prefix + s).Substring(txt.Length)) .ToArray(); return(new LineEditor.Completion(txt, res)); } // unknown command return(new LineEditor.Completion(txt, null)); } // list of commands res = cmds .Where(cmd => cmd.StartsWith(txt, StringComparison.OrdinalIgnoreCase)) .Select(cmd => cmd.Substring(txt.Length)) .ToArray(); return(new LineEditor.Completion(txt, res)); }; le.TabAtStartCompletes = true; string prompt = null; Action <string> updatePrompt = (path) => { prompt = String.Format("fdb:{0}> ", path); }; updatePrompt(CurrentDirectoryPath); while (!stop) { string s = startCommand != null ? startCommand : le.Edit(prompt, ""); startCommand = null; if (s == null) { break; } var tokens = s.Trim().Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string cmd = tokens.Length > 0 ? tokens[0] : String.Empty; string prm = tokens.Length > 1 ? tokens[1] : String.Empty; var extras = tokens.Length > 2 ? FdbTuple.CreateRange <string>(tokens.Skip(2)) : FdbTuple.Empty; var trimmedCommand = cmd.Trim().ToLowerInvariant(); switch (trimmedCommand) { case "": { continue; } case "log": { LogCommand(prm, Console.Out); break; } case "version": { await VersionCommand(prm, clusterFile, Console.Out, cancel); break; } case "tree": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Tree(path, extras, db, log, ct), cancel); break; } case "map": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Map(path, extras, db, log, ct), cancel); break; } case "dir": case "ls": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Dir(path, extras, BasicCommands.DirectoryBrowseOptions.Default, db, log, ct), cancel); break; } case "ll": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Dir(path, extras, BasicCommands.DirectoryBrowseOptions.ShowCount, db, log, ct), cancel); break; } case "count": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Count(path, extras, db, log, ct), cancel); break; } case "show": case "top": { var path = ParsePath(CurrentDirectoryPath); await RunAsyncCommand((db, log, ct) => BasicCommands.Show(path, extras, false, db, log, ct), cancel); break; } case "last": { var path = ParsePath(CurrentDirectoryPath); await RunAsyncCommand((db, log, ct) => BasicCommands.Show(path, extras, true, db, log, ct), cancel); break; } case "cd": case "pwd": { if (!string.IsNullOrEmpty(prm)) { var newPath = CombinePath(CurrentDirectoryPath, prm); var res = await RunAsyncCommand((db, log, ct) => BasicCommands.TryOpenCurrentDirectoryAsync(ParsePath(newPath), db, ct), cancel); if (res == null) { Console.WriteLine("# Directory {0} does not exist!", newPath); Console.Beep(); } else { CurrentDirectoryPath = newPath; updatePrompt(CurrentDirectoryPath); } } else { var res = await RunAsyncCommand((db, log, ct) => BasicCommands.TryOpenCurrentDirectoryAsync(ParsePath(CurrentDirectoryPath), db, ct), cancel); if (res.GetValueOrDefault() == null) { Console.WriteLine("# Directory {0} does not exist anymore", CurrentDirectoryPath); } else { Console.WriteLine("# {0}", res); } } break; } case "mkdir": case "md": { // "mkdir DIRECTORYNAME" if (!string.IsNullOrEmpty(prm)) { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.CreateDirectory(path, extras, db, log, ct), cancel); } break; } case "rmdir": { // "rmdir DIRECTORYNAME" if (!string.IsNullOrEmpty(prm)) { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.RemoveDirectory(path, extras, db, log, ct), cancel); } break; } case "mv": case "ren": { // "mv SOURCE DESTINATION" var srcPath = ParsePath(CombinePath(CurrentDirectoryPath, prm)); var dstPath = ParsePath(CombinePath(CurrentDirectoryPath, extras.Get <string>(0))); await RunAsyncCommand((db, log, ct) => BasicCommands.MoveDirectory(srcPath, dstPath, extras.Substring(1), db, log, ct), cancel); break; } case "layer": { if (string.IsNullOrEmpty(prm)) { // displays the layer id of the current folder var path = ParsePath(CurrentDirectoryPath); await RunAsyncCommand((db, log, ct) => BasicCommands.ShowDirectoryLayer(path, extras, db, log, ct), cancel); } else { // change the layer id of the current folder prm = prm.Trim(); // double or single quotes can be used to escape the value if (prm.Length >= 2 && (prm.StartsWith("'") && prm.EndsWith("'")) || (prm.StartsWith("\"") && prm.EndsWith("\""))) { prm = prm.Substring(1, prm.Length - 2); } var path = ParsePath(CurrentDirectoryPath); await RunAsyncCommand((db, log, ct) => BasicCommands.ChangeDirectoryLayer(path, prm, extras, db, log, ct), cancel); } break; } case "mkpart": { // "mkpart PARTITIONNAME" if (!string.IsNullOrEmpty(prm)) { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.CreateDirectory(path, FdbTuple.Create(FdbDirectoryPartition.LayerId).Concat(extras), db, log, ct), cancel); } break; } case "topology": { await RunAsyncCommand((db, log, ct) => BasicCommands.Topology(null, extras, db, log, ct), cancel); break; } case "shards": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Shards(path, extras, db, log, ct), cancel); break; } case "sampling": { var path = ParsePath(CombinePath(CurrentDirectoryPath, prm)); await RunAsyncCommand((db, log, ct) => BasicCommands.Sampling(path, extras, db, log, ct), cancel); break; } case "coordinators": { await RunAsyncCommand((db, log, ct) => CoordinatorsCommand(db, log, ct), cancel); break; } case "partition": { if (string.IsNullOrEmpty(prm)) { Console.WriteLine("# Current partition is {0}", String.Join("/", partition)); //TODO: browse existing partitions ? break; } var newPartition = prm.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); IFdbDatabase newDb = null; try { newDb = await ChangeDatabase(clusterFile, dbName, newPartition, cancel); } catch (Exception) { if (newDb != null) { newDb.Dispose(); } newDb = null; throw; } finally { if (newDb != null) { if (Db != null) { Db.Dispose(); Db = null; } Db = newDb; partition = newPartition; Console.WriteLine("# Changed partition to {0}", partition); } } break; } case "q": case "x": case "quit": case "exit": case "bye": { stop = true; break; } case "gc": { long before = GC.GetTotalMemory(false); Console.Write("Collecting garbage..."); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine(" Done"); long after = GC.GetTotalMemory(false); Console.WriteLine("- before = " + before.ToString("N0")); Console.WriteLine("- after = " + after.ToString("N0")); Console.WriteLine("- delta = " + (before - after).ToString("N0")); break; } case "mem": { Console.WriteLine("Memory usage:"); Console.WriteLine("- Working Set : " + PerfCounters.WorkingSet.NextValue().ToString("N0") + " (peak " + PerfCounters.WorkingSetPeak.NextValue().ToString("N0") + ")"); Console.WriteLine("- Virtual Bytes: " + PerfCounters.VirtualBytes.NextValue().ToString("N0") + " (peak " + PerfCounters.VirtualBytesPeak.NextValue().ToString("N0") + ")"); Console.WriteLine("- Private Bytes: " + PerfCounters.PrivateBytes.NextValue().ToString("N0")); Console.WriteLine("- Managed Mem : " + GC.GetTotalMemory(false).ToString("N0")); Console.WriteLine("- BytesInAlHeap: " + PerfCounters.ClrBytesInAllHeaps.NextValue().ToString("N0")); break; } case "wide": { Console.WindowWidth = 160; break; } case "status": case "wtf": { var result = await RunAsyncCommand((_, log, ct) => FdbCliCommands.RunFdbCliCommand("status details", null, clusterFile, log, ct), cancel); if (result.HasFailed) { break; } if (result.Value.ExitCode != 0) { Console.WriteLine("# fdbcli exited with code {0}", result.Value.ExitCode); Console.WriteLine("> StdErr:"); Console.WriteLine(result.Value.StdErr); Console.WriteLine("> StdOut:"); } Console.WriteLine(result.Value.StdOut); break; } default: { Console.WriteLine(string.Format("Unknown command : '{0}'", trimmedCommand)); break; } } if (!string.IsNullOrEmpty(execCommand)) { // only run one command, and then exit break; } } } finally { if (Db != null) { Db.Dispose(); } } }
public static void Main(string[] args) { var c = new WebDavConnection(); bool show_help = false; bool show_version = false; var o = new OptionSet { "Usage: webdav [OPTIONS]", "", "Simple WebDav command-line client to excercise WebDavClient.", "", "Options:", { "server=", "Set name of WebDAV {SERVER} to connect to.", v => c.Builder.Server = new Uri(v) }, { "user="******"Set {USERNAME} on WebDAV server to connect to.", v => (c.Builder.NetworkCredential ?? (c.Builder.NetworkCredential = new NetworkCredential())).UserName = v }, { "pass="******"Set {PASSWORD} on WebDAV server to connect to.", v => (c.Builder.NetworkCredential ?? (c.Builder.NetworkCredential = new NetworkCredential())).Password = v }, { "v", "Show verbose communication information.", v => c.Builder.Log = Console.Out }, { "version", "Show version information and exit.", v => show_version = v != null }, { "help|h|?", "Show this message and exit.", v => show_help = v != null }, }; try { o.Parse(args); } catch (Exception ex) { Console.Error.WriteLine("webdav: {0}", ex.Message); } if (show_version) { Console.WriteLine("webdav 0.1"); return; } if (show_help) { o.WriteOptionDescriptions(Console.Out); return; } LineEditor e = new LineEditor("webdav"); string s; while ((s = e.Edit("webdav> ", "")) != null) { if ((s = s.Trim()).Length == 0) { continue; } var p = s.IndexOf(' '); var m = p < 0 ? s : s.Substring(0, p); var a = WebDavConnection.GetCommand(m); if (a == null) { Console.Error.WriteLine("webdav: Invalid command: {0}", s); continue; } while (p > 0 && p < s.Length && char.IsWhiteSpace(s, p)) { ++p; } s = p >= 0 && p < s.Length ? s.Substring(p) : ""; a(c, s); } }
public static int Main(string[] args) { var show_help = false; var use_precompiled = true; var options = new OptionSet { { "p|no-precomp", "do not use precompiled libraries", v => use_precompiled = v == null }, { "h|help", "show this message and exit", v => show_help = v != null } }; List <string> files; try { files = options.Parse(args); } catch (OptionException e) { Console.Error.Write(AppDomain.CurrentDomain.FriendlyName + ": "); Console.Error.WriteLine(e.Message); Console.Error.WriteLine("Try “" + AppDomain.CurrentDomain.FriendlyName + " --help” for more information."); return(1); } if (show_help) { Console.WriteLine("Usage: " + AppDomain.CurrentDomain.FriendlyName + " input.flbgst"); Console.WriteLine("Run Flabbergast interactively."); Console.WriteLine(); Console.WriteLine("Options:"); options.WriteOptionDescriptions(Console.Out); return(1); } if (files.Count > 1) { Console.Error.WriteLine("No more than one Flabbergast script may be given."); return(1); } Frame original = null; var assembly_builder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("Repl"), AssemblyBuilderAccess.Run); var module_builder = assembly_builder.DefineDynamicModule("ReplModule"); var unit = new CompilationUnit(module_builder, false); var collector = new ConsoleCollector(); var task_master = new ConsoleTaskMaster(); task_master.AddUriHandler(BuiltInLibraries.INSTANCE); if (use_precompiled) { task_master.AddUriHandler(new LoadPrecompiledLibraries()); } task_master.AddUriHandler(new DynamicallyCompiledLibraries(collector)); if (files.Count == 1) { var parser = Parser.Open(files[0]); var root_type = parser.ParseFile(collector, unit, "REPLRoot"); if (root_type != null) { var computation = (Computation)Activator.CreateInstance(root_type, task_master); computation.Notify(r => original = r as Frame); task_master.Slot(computation); task_master.Run(); task_master.ReportCircularEvaluation(); } } if (original == null) { original = new Frame(task_master, task_master.NextId(), new SourceReference("<repl>", "<native>", 0, 0, 0, 0, null), null, null); } var id = 0; Frame current = original; bool run = true; ConsumeResult update_current = (x) => current = (x as Frame) ?? current; var line_editor = new LineEditor("flabbergast"); var completables = new Completables(); line_editor.AutoCompleteEvent = completables.Handler; string s; while (run && (s = line_editor.Edit(id + "‽ ", "")) != null) { var parser = new Parser("line" + id, s); var run_type = parser.ParseRepl(collector, unit, "REPL" + id++); if (run_type != null) { object result = null; var computation = (Computation)Activator.CreateInstance(run_type, new object[] { task_master, original, current, update_current, (ConsumeResult)(output => result = output), (ConsumeResult)Console.WriteLine }); computation.Notify(r => run = (r as bool?) ?? true); task_master.Slot(computation); task_master.Run(); if (result != null) { HandleResult(result); } task_master.ReportCircularEvaluation(); } } line_editor.SaveHistory(); return(0); }
public static void Main(string[] args) { const int width = 1024 * 4; const int height = 1024 * 4; // var versionVar = RT.var("clojure.core", "clojure-version"); // var serverStartVar = RT.var("clojure.core.server", "start-server"); // var ednReadVar = RT.var("clojure.edn", "read-string"); // var serverOptions = ednReadVar.invoke("{:name \"pico\" :port 1987 :accept clojure.core.server/repl}"); // Console.WriteLine("Clojure {0} listening on port {1}", versionVar.invoke(), 1987); // serverStartVar.invoke(serverOptions); using (var game = new GameWindow(width, height, GraphicsMode.Default, "Pico", GameWindowFlags.Default, DisplayDevice.Default, 4, 5, GraphicsContextFlags.Default)) { Demo d = new Demo(); StatusPrint(GetPName.MaxUniformBlockSize); game.Load += (sender, e) => { // setup settings, load textures, sounds d.Initialize(); game.VSync = VSyncMode.On; StatusPrint(StringName.Renderer); StatusPrint(StringName.ShadingLanguageVersion); StatusPrint(StringName.Vendor); StatusPrint(StringName.Version); new Thread(() => { var readString = RT.var("clojure.core", "read-string"); var eval = RT.var("clojure.core", "eval"); var prStr = RT.var("clojure.core", "pr-str"); var le = new LineEditor("pico"); var nsVar = RT.var("clojure.core", "*ns*"); Var.pushThreadBindings(RT.mapUniqueKeys(nsVar, Namespace.find(Symbol.intern("user")))); try { string input; var sb = new StringBuilder(); while ((input = le.Edit( sb.Length == 0 ? $"{nsVar.deref()}> " : new string('.', $"{nsVar.deref()}> ".Length), "")) != null) { if (input == "::panic!") { sb.Clear(); continue; } sb.AppendLine(input); try { Console.WriteLine(prStr.invoke(eval.invoke(readString.invoke(sb.ToString())))); sb.Clear(); } catch (EndOfStreamException exception) { } catch (Exception exception) { Console.WriteLine("{0} {1}", exception.GetType(), exception.Message); sb.Clear(); } } } finally { Var.popThreadBindings(); } }).Start(); }; game.RenderFrame += (sender, e) => { GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); foreach (var parameter in Demo.parameters) { parameter.Interpolate((float)e.Time); } d.Draw(game.Width, game.Height, e.Time); game.SwapBuffers(); Demo._fps = game.RenderFrequency; // TODO grab fps // TODO grab frame render time }; game.Resize += (sender, e) => { GL.Viewport(0, 0, game.Width, game.Height); }; game.Run(60.0); } }
internal static void Run(Version ver, bool batch, bool rc, IEnumerable <string> commands, IEnumerable <string> files) { if (!Configuration.Read()) { Configuration.Defaults(); } Configuration.Apply(); var dbFile = Configuration.Current.DefaultDatabaseFile; if (Configuration.Current.LoadDatabaseAutomatically && !string.IsNullOrWhiteSpace(dbFile)) { FileInfo file; try { file = new FileInfo(dbFile); } catch (Exception ex) { Log.Error("Could not open database file '{0}':", dbFile); Log.Error(ex.ToString()); return; } Debugger.Read(file); } Log.Notice("Welcome to the Mono soft debugger (sdb {0})", ver); Log.Notice("Type 'help' for a list of commands or 'quit' to exit"); Log.Info(string.Empty); Root.AddCommands(Plugins.LoadDefault()); var rcFile = GetFilePath(); if (rc && File.Exists(rcFile)) { RunFile(rcFile, true); } foreach (var file in files) { if (File.Exists(file)) { RunFile(file, true); } } RunCommands(commands); while (!Stop) { // If the command caused the debuggee to start // or resume execution, wait for it to suspend. if (InferiorExecuting) { ResumeEvent.WaitOne(); InferiorExecuting = false; } string cmd; // We use a queue here so that batch commands are // also subject to the suspension check above. It // also makes things easier since everything gets // executed in one thread. if (_queue.TryDequeue(out cmd)) { Process(cmd, true); } else if (batch) { Stop = true; } else { cmd = _lineEditor != null? _lineEditor.Edit(GetPrompt(), string.Empty) : LibEdit.ReadLine(GetPrompt()); // Did we get EOF? if (cmd == null) { Log.Info(string.Empty); if (Debugger.State != State.Exited) { Log.Error("An inferior process is active"); } else { Stop = true; } } else { Process(cmd, false); } } } // Clean up just in case. UnsetControlCHandler(); dbFile = Configuration.Current.DefaultDatabaseFile; if (Configuration.Current.SaveDatabaseAutomatically && !string.IsNullOrWhiteSpace(dbFile)) { FileInfo file; try { file = new FileInfo(dbFile); } catch (Exception ex) { Log.Error("Could not open database file '{0}':", dbFile); Log.Error(ex.ToString()); return; } Debugger.Write(file); } // Let's not leave dead Mono processes behind... Debugger.Pause(); Debugger.Kill(); while (!Debugger.DebuggeeKilled) { Thread.Sleep(10); } Log.Notice("Bye"); }
private string ProcessInput() { return(le.Edit(GetPromptString(), "")); }
public string Edit(string prompt, string initial = null) { return(LineEditor.Edit(prompt, initial ?? string.Empty)); }
/// <summary> /// Hosts an interactive REPL against a supported Workbooks target platform. /// This is analogous to 'csharp' or 'csi' or any other REPL on the planet. /// </summary> static async Task <int> ReplPlayerMain(InteractiveSession session) { // As an exercise to the reader, this puppy should take an optional // workbook flavor ID to know what platform you want to REPL and find // it in the list of installed and available ones... // For now we'll just pick the first available option 😺 var workbookTarget = WorkbookAppInstallation.All.FirstOrDefault(); if (workbookTarget == null) { RenderError("No workbook target platforms could be found."); return(1); } // We do not currently expose a list of available language descriptions // for the given build/installation, but if we did, this is when // you'd want to pick one. Just assume 'csharp' for now. Stay tuned. language = "csharp"; // A session description combines just enough info for the entire // EvaluationService to get itself in order to do your bidding. var sessionDescription = new InteractiveSessionDescription( language, workbookTarget.Id, new EvaluationEnvironment(Environment.CurrentDirectory)); // And initialize it with all of our prerequisites... // Status events raised within this method will be posted to the // observable above ("starting agent", "initializing workspace", etc). await session.InitializeAsync(sessionDescription); CodeCellId cellId = default; var editor = new LineEditor("xic"); editor.BeforeRenderPrompt = () => ForegroundColor = ConsoleColor.Yellow; editor.AfterRenderPrompt = () => ResetColor(); // At this point we have the following in order, ready to serve: // // 1. a connected agent ready to execute code // 2. a workspace that can perform compliation, intellisense, etc // 3. an evaluation service that is ready to deal with (1) and (2) // // It's at this point that a full UI would allow the user to actually // run code. This is the "User Experience main()"... // // This is the REPL you're looking for... while (true) { // append a new cell (no arguments here imply append) cellId = await session.EvaluationService.InsertCodeCellAsync(); for (int i = 0; true; i++) { var deltaBuffer = editor.Edit( GetPrompt(i > 0), null); var existingBuffer = await session.EvaluationService.GetCodeCellBufferAsync(cellId); await session.EvaluationService.UpdateCodeCellAsync( cellId, existingBuffer.Value + deltaBuffer); if (session.WorkspaceService.IsCellComplete(cellId)) { break; } } var finishedEvent = await session.EvaluationService.EvaluateAsync(cellId); // if the evaluation was not successful, remove the cell so it's not internally // re-evaluated (which would continue to yield the same failures) if (finishedEvent.Status != CodeCellEvaluationStatus.Success) { await session.EvaluationService.RemoveCodeCellAsync(finishedEvent.CodeCellId); } } }
public void Play(string name) { using (var listener = new System.Timers.Timer(200)) using (var player = GetPlayer(name)) { _input.Focus(); var le = new LineEditor(_input, _completionPopup, "dungeon") { TabAtStartCompletes = true, AutoCompleteEvent = AutoComplete }; _view.WriteLine(player.Look()); string line = ""; listener.Elapsed += (sender, args) => { lock (_view) { foreach (var heard in player.Listen()) { _view.WriteLine(heard); } } }; listener.Start(); while ((line = le.Edit(GetPrompt(player), "")) != null) { lock (_view) { var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) { continue; } var handled = true; switch (parts[0]) { case "quit": return; case "l": case "look": _view.WriteLine(player.Look()); break; case "n": _view.WriteLine(player.Go(Direction.North)); break; case "s": _view.WriteLine(player.Go(Direction.South)); break; case "e": _view.WriteLine(player.Go(Direction.East)); break; case "w": _view.WriteLine(player.Go(Direction.West)); break; case "u": _view.WriteLine(player.Go(Direction.Up)); break; case "d": _view.WriteLine(player.Go(Direction.Down)); break; case "go": if (parts.Length < 2) { break; } Direction direction; Enum.TryParse(parts[1], true, out direction); _view.WriteLine(player.Go(direction)); break; case "say": if (parts.Length < 2) { _view.WriteLine("you gotta say something"); continue; } var said = string.Join(" ", parts.Skip(1)); player.Say(said); break; case "debug": if (_debug.IsVisible) { _debug.Hide(); _view.Top = 0; _view.Height = Console.WindowHeight - 3; } else { _debug.Show(); _view.Top = _viewTop; _view.Height = _viewHeight; } break; default: handled = false; break; } if (!handled) { _view.WriteLine("Unknown command: {0}", line); _view.WriteLine(); } } } } }
/// <summary> /// Entry point for the rcl interpreter /// </summary> public void InstanceMain(string[] argv, string appDomainVersionString) { string flags = Environment.GetEnvironmentVariable("RCL_FLAGS"); RCLArgv cmd; if (flags != null) { string[] flagsv = flags.Split(' '); string[] newArgv = new string[flagsv.Length + argv.Length]; for (int i = 0; i < flagsv.Length; ++i) { newArgv[i] = flagsv[i]; } for (int i = 0; i < argv.Length; ++i) { newArgv[flagsv.Length + i] = argv[i]; } cmd = RCLArgv.Init(newArgv); } else { cmd = RCLArgv.Init(argv); } // Someday do color output like this // string message = "\x1b[0;33mYELLOW\x1b[0;31m RED\x1b[0;34m BLUE\x1b[0;37m"; // Initialize runner environment AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( UnhandledException); string prompt = "RCL>"; LineEditor editor = new LineEditor("RCL"); RCRunner runner = new RCRunner(workers: 1); InstallSignalHandler(runner); cmd.PrintStartup(appDomainVersionString); string line = ""; if (cmd.Program != "" || IsolateCode != null) { int status = 0; RCValue codeResult = null; try { RCValue code = null; if (IsolateCode != null) { code = runner.Read(IsolateCode); } else if (cmd.Program != "") { string file = File.ReadAllText(cmd.Program, Encoding.UTF8); code = runner.Read(file); } codeResult = runner.Rep(code, restoreStateOnError: true); if (cmd.Action != "") { RCValue result = runner.RepAction(cmd.Action); if (cmd.OutputEnum != RCOutput.Clean && !cmd.NoResult) { Console.Out.WriteLine(result.Format(RCFormat.Pretty, RCSystem.Log.GetColmap())); } } if (cmd.Batch && !cmd.Exit) { Thread.Sleep(Timeout.Infinite); } if (cmd.Batch) { status = runner.ExitStatus(); runner.Dispose(); Environment.Exit(status); } // otherwise go on and keep listening for further commands. } catch (ThreadAbortException) { status = runner.ExitStatus(); runner.Dispose(); Environment.Exit(status); } catch (ArgumentException ex) { // This is for when the action name is not in _state. RCSystem.Log.Record(0, 0, "runner", 0, "fatal", ex); Environment.Exit(1); } catch (FileNotFoundException ex) { // This for when the program file cannot be read. RCSystem.Log.Record(0, 0, "runner", 0, "fatal", ex); Environment.Exit(1); } catch (RCSyntaxException ex) { // Program file has bad syntax RCSystem.Log.Record(0, 0, "runner", 0, "fatal", ex); Environment.Exit(2); } catch (Exception ex) { // For all other exceptions keep the process open unless instructed to --exit. // This is so you can hack around in the environment. // Does this result in duplicate exception reports on the console? // I don't want it to, but without this there are errors that do not show up at // all. RCSystem.Log.Record(0, 0, "fiber", 0, "fatal", ex); status = runner.ExitStatus(); if (IsolateCode != null) { AppDomain.CurrentDomain.SetData("IsolateException", ex); } } finally { if (codeResult != null) { IsolateResult = codeResult.ToString(); AppDomain.CurrentDomain.SetData("IsolateResult", IsolateResult); } if (cmd.Exit) { runner.Dispose(); Environment.Exit(status); } } if (IsolateCode != null) { // When running isolated, do not call Environment.Exit because it would close // the entire // process. runner.Dispose(); return; } } else if (cmd.Exit && !cmd.Batch) { int status = runner.ExitStatus(); runner.Dispose(); // This means there is no program and no input from stdin. // The process simply starts and then stops. // There is no way external way to cause an error to be generated, // so there is no test for the possible non-zero status result. Environment.Exit(status); } // Process batch (standard input) and interactive commands. while (true) { int status = 0; try { if (cmd.Batch) { StringBuilder text = new StringBuilder(); // Read all commands from standard input. while (true) { line = Console.ReadLine(); if (line == null) { break; } text.AppendLine(line); } bool fragment; RCValue code = RCSystem.Parse(text.ToString(), out fragment); RCValue codeResult = runner.Rep(code, restoreStateOnError: true); if (cmd.Action != "") { RCValue actionResult = runner.RepAction(cmd.Action); if (cmd.OutputEnum != RCOutput.Clean && !cmd.NoResult) { Console.Out.WriteLine(actionResult.Format(RCFormat.Pretty, RCSystem.Log.GetColmap())); } } else if (codeResult != null && !cmd.NoResult) { Console.Out.WriteLine(codeResult.Format(RCFormat.Pretty, RCSystem.Log.GetColmap())); } if (cmd.Exit) { status = runner.ExitStatus(); runner.Dispose(); Environment.Exit(status); } } else { if (cmd.NoKeys) { // No read requires nokeys to have an effect, obvs. if (cmd.NoRead) { Thread.Sleep(Timeout.Infinite); } else { line = Console.ReadLine(); } } else { line = editor.Edit(prompt, ""); } _firstSigint = false; if (line != null) { string trimmed = line.TrimStart(' ').TrimEnd(' '); line = Alias(trimmed, runner, cmd); RCValue result = runner.Rep(line, restoreStateOnError: false); if (result != null) { Console.Out.WriteLine(result.Format(RCFormat.Pretty, RCSystem.Log.GetColmap())); } } else { break; } } } catch (ThreadAbortException) { status = runner.ExitStatus(); runner.Dispose(); // This prevents the last RCL prompt from appearing on the same line as the next // bash // prompt. // I want to do something so that log output *never* appears on the same line as // the // prompt. Console.Out.Flush(); Environment.Exit(status); } catch (Exception ex) { // Prevent having duplicate output in the log for these. // Also allow the runner to report this exception and count it towards // determination of // exit status. if (!runner.RunnerUnhandled) { runner.Report(ex, "unhandled"); } } } runner.Dispose(); Environment.Exit(0); }
public string ReadLine(string prompt) { return(_editor.Edit(prompt, "")); }
public string Edit(string prompt, string initial = null) => _lineEditor.Edit(prompt, initial);
private static async Task MainAsync(string[] args, CancellationToken cancel) { #region Options Parsing... string clusterFile = null; var partition = FdbPath.Root; bool showHelp = false; int timeout = 30; int maxRetries = 10; string execCommand = null; var opts = new OptionSet() { { "c|C|connfile=", "The path of a file containing the connection string for the FoundationDB cluster.", v => clusterFile = v }, { "p|partition=", "The name of the database partition to open.", v => partition = FdbPath.Parse(v.Trim()) }, { "t|timeout=", "Default timeout (in seconds) for failed transactions.", (int v) => timeout = v }, { "r|retries=", "Default max retry count for failed transactions.", (int v) => maxRetries = v }, { "exec=", "Execute this command, and exits immediately.", v => execCommand = v }, { "h|help", "Show this help and exit.", v => showHelp = v != null } }; var extra = opts.Parse(args); if (showHelp) { //TODO! opts.WriteOptionDescriptions(Console.Out); return; } string startCommand = null; if (!string.IsNullOrEmpty(execCommand)) { startCommand = execCommand; } else if (extra.Count > 0) { // the remainder of the command line will be the first command to execute startCommand = String.Join(" ", extra); } #endregion bool stop = false; Db = null; try { var cnxOptions = new FdbConnectionOptions { ClusterFile = clusterFile, Root = partition }; Db = await ChangeDatabase(cnxOptions, cancel); Db.DefaultTimeout = Math.Max(0, timeout) * 1000; Db.DefaultRetryLimit = Math.Max(0, maxRetries); StdOut("Using API v" + Fdb.ApiVersion + " (max " + Fdb.GetMaxApiVersion() + ")", ConsoleColor.Gray); StdOut("Cluster file: " + (clusterFile ?? "<default>"), ConsoleColor.Gray); StdOut(""); StdOut("FoundationDB Shell menu:"); StdOut("\tcd\tChange the current directory"); StdOut("\tdir\tList the sub-directories the current directory"); StdOut("\tshow\tShow the content of the current directory"); StdOut("\ttree\tShow all the directories under the current directory"); StdOut("\tsampling\tDisplay statistics on random shards from the database"); StdOut("\tcoordinators\tShow the current coordinators for the cluster"); //StdOut("\thelp\tShow all the commands"); StdOut("\tquit\tQuit"); StdOut(""); try { var cf = await Fdb.System.GetCoordinatorsAsync(Db, cancel); Description = cf.Description; StdOut("Ready...", ConsoleColor.DarkGreen); } catch (Exception e) { StdErr("Failed to get coordinators state from cluster: " + e.Message, ConsoleColor.DarkRed); Description = "???"; } StdOut(""); var le = new LineEditor("FDBShell"); string[] cmds = new string[] { "cd", "clear", "coordinators", "count", "dir", "dump", "exit", "gc", "help", "layer", "map", "mem", "mkdir", "mv", "partition", "pwd", "quit", "ren", "rmdir", "sampling", "shards", "show", "status", "topology", "tree", "version", "wide", }; le.AutoCompleteEvent = (txt, pos) => { string[] res; int p = txt.IndexOf(' '); if (p > 0) { string cmd = txt.Substring(0, p); string arg = txt.Substring(p + 1).Trim(); if (cmd == "cd" || cmd == "rmdir") { // handle completion for directories // txt: "cd foo" => prefix = "foo" // txt: "cd foobar/b" => prefix = "b" bool hasLeadingSlash = arg.EndsWith("/"); var path = FdbPath.Parse(hasLeadingSlash ? (arg + "!") : arg); var parent = path.Count > 1 ? path.GetParent() : path.IsAbsolute ? FdbPath.Root : FdbPath.Empty; string search = hasLeadingSlash ? "" : path.Name; var subdirs = RunAsyncCommand((db, log, ct) => AutoCompleteDirectories(CombinePath(CurrentDirectoryPath, parent.ToString()), db, log, ct), cancel).GetAwaiter().GetResult(); if (!subdirs.HasValue || subdirs.Value == null) { return(new LineEditor.Completion(txt, null)); } res = subdirs.Value .Where(s => s.StartsWith(search, StringComparison.Ordinal)) .Select(s => (cmd + " " + parent[s]).Substring(txt.Length)) .ToArray(); if (res.Length == 1 && res[0] == string.Empty) { // someone was at "cd /Foo/Bar", pressed TAB again, and there is no other match // => we interpret it as "want to go in the sub-folder res = new[] { "/" }; // add a "slash" } return(new LineEditor.Completion(txt, res)); } // unknown command return(new LineEditor.Completion(txt, null)); } // list of commands res = cmds .Where(cmd => cmd.StartsWith(txt, StringComparison.OrdinalIgnoreCase)) .Select(cmd => cmd.Substring(txt.Length)) .ToArray(); return(new LineEditor.Completion(txt, res)); }; le.TabAtStartCompletes = true; string prompt = null; void UpdatePrompt(FdbPath path) { prompt = $"[fdb:{Description} {path.ToString()}]# "; } le.PromptColor = ConsoleColor.Cyan; UpdatePrompt(CurrentDirectoryPath); while (!stop) { string s; if (startCommand != null) { s = startCommand; startCommand = null; } else { s = startCommand ?? le.Edit(prompt, ""); } if (s == null) { break; } //TODO: we need a tokenizer that recognizes binary keys, tuples, escaped paths, etc... var tokens = Tokenize(s); string cmd = tokens.Count > 0 ? tokens.Get <string>(0) : string.Empty; var extras = tokens.Count > 1 ? tokens.Substring(1) : STuple.Empty; var trimmedCommand = cmd.Trim().ToLowerInvariant(); try { switch (trimmedCommand) { case "": { continue; } case "log": { string prm = PopParam(ref extras); LogCommand(prm, extras, Console.Out); break; } case "version": { await VersionCommand(extras, clusterFile, Console.Out, cancel); break; } case "tree": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Tree(path, extras, db, log, ct), cancel); break; } case "map": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Map(path, extras, db, log, ct), cancel); break; } case "dir": case "ls": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Dir(path, extras, BasicCommands.DirectoryBrowseOptions.Default, db, log, ct), cancel); break; } case "ll": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Dir(path, extras, BasicCommands.DirectoryBrowseOptions.ShowCount, db, log, ct), cancel); break; } case "count": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Count(path, extras, db, log, ct), cancel); break; } case "show": case "top": { await RunAsyncCommand((db, log, ct) => BasicCommands.Show(CurrentDirectoryPath, extras, false, db, log, ct), cancel); break; } case "last": { await RunAsyncCommand((db, log, ct) => BasicCommands.Show(CurrentDirectoryPath, extras, true, db, log, ct), cancel); break; } case "dump": { string output = PopParam(ref extras); if (string.IsNullOrEmpty(output)) { StdErr("You must specify a target file path.", ConsoleColor.Red); break; } await RunAsyncCommand((db, log, ct) => BasicCommands.Dump(CurrentDirectoryPath, output, extras, db, log, ct), cancel); break; } case "cd": case "pwd": { string prm = PopParam(ref extras); if (!string.IsNullOrEmpty(prm)) { var newPath = CombinePath(CurrentDirectoryPath, prm); var res = await RunAsyncCommand( (db, log, ct) => db.ReadAsync(tr => BasicCommands.TryOpenCurrentDirectoryAsync(tr, newPath), ct), cancel ); if (res.Failed) { StdErr($"# Failed to open Directory {newPath}: {res.Error.Message}", ConsoleColor.Red); Console.Beep(); } else if (res.Value == null) { StdOut($"# Directory {newPath} does not exist!", ConsoleColor.Red); Console.Beep(); } else { CurrentDirectoryPath = newPath; UpdatePrompt(CurrentDirectoryPath); } } else { var res = await RunAsyncCommand( (db, log, ct) => db.ReadAsync(tr => BasicCommands.TryOpenCurrentDirectoryAsync(tr, CurrentDirectoryPath), ct), cancel ); if (res.Failed) { StdErr($"# Failed to query Directory {Program.CurrentDirectoryPath}: {res.Error.Message}", ConsoleColor.Red); } else if (res.Value == null) { StdOut($"# Directory {Program.CurrentDirectoryPath} does not exist anymore"); } } break; } case "mkdir": case "md": { // "mkdir DIRECTORYNAME" string prm = PopParam(ref extras); if (!string.IsNullOrEmpty(prm)) { var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.CreateDirectory(path, extras, db, log, ct), cancel); } break; } case "rmdir": { // "rmdir DIRECTORYNAME" string prm = PopParam(ref extras); if (!string.IsNullOrEmpty(prm)) { var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.RemoveDirectory(path, extras, db, log, ct), cancel); } break; } case "mv": case "ren": { // "mv SOURCE DESTINATION" string prm = PopParam(ref extras); var srcPath = CombinePath(CurrentDirectoryPath, prm); var dstPath = CombinePath(CurrentDirectoryPath, extras.Get <string>(0)); await RunAsyncCommand((db, log, ct) => BasicCommands.MoveDirectory(srcPath, dstPath, extras.Substring(1), db, log, ct), cancel); break; } case "get": { // "get KEY" if (extras.Count == 0) { StdErr("You must specify a key to read.", ConsoleColor.Red); break; } await RunAsyncCommand((db, log, ct) => BasicCommands.Get(CurrentDirectoryPath, extras, db, log, ct), cancel); break; } case "clear": { // "clear KEY" if (extras.Count == 0) { StdErr("You must specify a key to clear.", ConsoleColor.Red); break; } await RunAsyncCommand((db, log, ct) => BasicCommands.Clear(CurrentDirectoryPath, extras, db, log, ct), cancel); break; } case "clearrange": { // "clear *" or "clear FROM TO" if (extras.Count == 0) { StdErr("You must specify either '*', a prefix, or a key range.", ConsoleColor.Red); break; } await RunAsyncCommand((db, log, ct) => BasicCommands.ClearRange(CurrentDirectoryPath, extras, db, log, ct), cancel); break; } case "layer": { string prm = PopParam(ref extras); if (string.IsNullOrEmpty(prm)) { // displays the layer id of the current folder await RunAsyncCommand((db, log, ct) => BasicCommands.ShowDirectoryLayer(CurrentDirectoryPath, extras, db, log, ct), cancel); } else { // change the layer id of the current folder prm = prm.Trim(); // double or single quotes can be used to escape the value if (prm.Length >= 2 && (prm.StartsWith("'") && prm.EndsWith("'")) || (prm.StartsWith("\"") && prm.EndsWith("\""))) { prm = prm.Substring(1, prm.Length - 2); } await RunAsyncCommand((db, log, ct) => BasicCommands.ChangeDirectoryLayer(CurrentDirectoryPath, prm, extras, db, log, ct), cancel); } break; } case "mkpart": { // "mkpart PARTITIONNAME" string prm = PopParam(ref extras); if (!string.IsNullOrEmpty(prm)) { var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.CreateDirectory(path, STuple.Create(FdbDirectoryPartition.LayerId).Concat(extras), db, log, ct), cancel); } break; } case "topology": { await RunAsyncCommand((db, log, ct) => BasicCommands.Topology(null, extras, db, log, ct), cancel); break; } case "shards": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Shards(path, extras, db, log, ct), cancel); break; } case "sampling": { string prm = PopParam(ref extras); var path = CombinePath(CurrentDirectoryPath, prm); await RunAsyncCommand((db, log, ct) => BasicCommands.Sampling(path, extras, db, log, ct), cancel); break; } case "coordinators": { await RunAsyncCommand((db, log, ct) => CoordinatorsCommand(db, log, ct), cancel); break; } case "partition": { string prm = PopParam(ref extras); if (string.IsNullOrEmpty(prm)) { StdOut($"# Current partition is {partition}"); //TODO: browse existing partitions ? break; } var newPartition = FdbPath.Parse(prm.Trim()); IFdbDatabase newDb = null; try { var options = new FdbConnectionOptions { ClusterFile = clusterFile, Root = newPartition }; newDb = await ChangeDatabase(options, cancel); } catch (Exception) { newDb?.Dispose(); newDb = null; throw; } finally { if (newDb != null) { if (Db != null) { Db.Dispose(); Db = null; } Db = newDb; partition = newPartition; StdOut($"# Changed partition to {partition}"); } } break; } case "q": case "x": case "quit": case "exit": case "bye": { stop = true; break; } case "gc": { long before = GC.GetTotalMemory(false); Console.Write("Collecting garbage..."); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); StdOut(" Done"); long after = GC.GetTotalMemory(false); StdOut("- before = " + before.ToString("N0")); StdOut("- after = " + after.ToString("N0")); StdOut("- delta = " + (before - after).ToString("N0")); break; } case "mem": { StdOut("Memory usage:"); StdOut("- Managed Mem : " + GC.GetTotalMemory(false).ToString("N0")); //TODO: how do we get these values on Linux/Mac? #if !NETCOREAPP StdOut("- Working Set : " + PerfCounters.WorkingSet.NextValue().ToString("N0") + " (peak " + PerfCounters.WorkingSetPeak.NextValue().ToString("N0") + ")"); StdOut("- Virtual Bytes: " + PerfCounters.VirtualBytes.NextValue().ToString("N0") + " (peak " + PerfCounters.VirtualBytesPeak.NextValue().ToString("N0") + ")"); StdOut("- Private Bytes: " + PerfCounters.PrivateBytes.NextValue().ToString("N0")); StdOut("- BytesInAlHeap: " + PerfCounters.ClrBytesInAllHeaps.NextValue().ToString("N0")); #endif break; } case "wide": { try { Console.WindowWidth = 160; } catch (Exception e) { StdErr("Failed to change console width: " + e.Message, ConsoleColor.DarkRed); } break; } case "status": case "wtf": { var result = await RunAsyncCommand((_, log, ct) => FdbCliCommands.RunFdbCliCommand("status details", null, clusterFile, log, ct), cancel); if (result.Failed) { break; } if (result.Value.ExitCode != 0) { StdErr($"# fdbcli exited with code {result.Value.ExitCode}", ConsoleColor.DarkRed); StdOut("> StdErr:", ConsoleColor.DarkGray); StdOut(result.Value.StdErr); StdOut("> StdOut:", ConsoleColor.DarkGray); } StdOut(result.Value.StdOut); break; } default: { StdErr($"Unknown command : '{trimmedCommand}'", ConsoleColor.Red); break; } } } catch (Exception e) { StdErr($"Failed to execute command '{trimmedCommand}': " + e.Message, ConsoleColor.Red); #if DEBUG StdErr(e.ToString(), ConsoleColor.DarkRed); #endif } if (!string.IsNullOrEmpty(execCommand)) { // only run one command, and then exit break; } } } finally { Program.Db?.Dispose(); } }
private static void Main(string[] args) { Container = BootStrapper.Components(); Console.CancelKeyPress += BreakConsole; if (args.Length == 0) { ShowHelp(); return; } var param0 = args[0].ToLowerInvariant(); if (args.Length == 2 && param0 == "--scan") { CreateCache(args[1]); } else if (args.Length == 2 && param0 == "--scan2") { CreateCache2(args[1]); } else if (args.Length == 2 && Find.FindParams.Contains(param0)) { Find.StaticFind(args[1], param0); } else if (args.Length == 2 && param0 == "--replgreppath") { FindRepl(Find.ParamGreppath, args[1]); } else if (args.Length == 2 && param0 == "--replgrep") { FindRepl(Find.ParamGrep, args[1]); } else if (args.Length == 2 && param0 == "--replfind") { FindRepl(Find.ParamFind, args[1]); } else if (args.Length == 1 && param0 == "--hash") { CreateMd5OnCache(); } else if (args.Length == 1 && param0 == "--hash2") { CreateMd5OnCache2(); } else if (args.Length == 1 && param0 == "--dupes") { FindDupes(); } else if (args.Length == 1 && param0 == "--treedump1") { PrintPathsHaveHashEnumerator(); } else if (args.Length == 1 && param0 == "--treedump2") { EntryStore.PrintPathsHaveHash(); } else if (args.Length == 1 && param0 == "--version") { Console.WriteLine(Version); } else if (args.Length == 1 && param0 == "--loadwait") { Console.WriteLine(Version); RootEntry.LoadCurrentDirCache(); Console.ReadLine(); } else if (args.Length == 1 && param0 == "--loadwait2") { Console.WriteLine(Version); EntryStore.LoadCurrentDirCache(); Console.ReadLine(); } else if (args.Length == 1 && param0 == "--repl") { var le = new LineEditor(null); string s; var running = true; while (running && (s = le.Edit("shell> ", string.Empty)) != null) { Console.WriteLine($"----> [{s}]"); switch (s) { case "quit": running = false; break; case "history": case "!": le.CmdHistoryDump(); break; case "help": case "?": Console.WriteLine("Builtin Commands:"); Console.WriteLine(" quit - quit, "); Console.WriteLine(" help - show help, ? - show help"); Console.WriteLine(" history - show history, ! - show history"); Console.WriteLine("Keystrokes:"); Console.WriteLine(" Home, End, Left, Right, Up, Down, Back, Del, Tab"); Console.WriteLine(" C-a, C-e, C-b, C-f, C-p, C-n, C-d"); Console.WriteLine(" C-l - clear console to top"); Console.WriteLine(" C-r - reverse seach history"); Console.WriteLine(" A-b - move backward word"); Console.WriteLine(" A-f - move forward word"); Console.WriteLine(" A-d - delete word forward"); Console.WriteLine(" A-Backspace - delete word backward"); break; } } } else if (args.Length == 2 && param0 == "--populousfolders") { int count; if (int.TryParse(args[1], out count)) { FindPouplous(count); } else { Console.WriteLine("Populous folders option requires an integer as second parameter"); } } else { ShowHelp(); } }