forked from litedb-org/LiteDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InputCommand.cs
112 lines (90 loc) · 2.85 KB
/
InputCommand.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace LiteDB.Shell
{
public class InputCommand
{
public Queue<string> Queue { get; set; }
public List<string> History { get; set; }
public Stopwatch Timer { get; set; }
public bool Running { get; set; }
public bool AutoExit { get; set; }
public Action<string> OnWrite { get; set; }
public InputCommand()
{
this.Queue = new Queue<string>();
this.History = new List<string>();
this.Timer = new Stopwatch();
this.Running = true;
this.AutoExit = false; // run "exit" command when there is not more command in queue
}
public string ReadCommand()
{
if (this.Timer.IsRunning)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
this.Write(this.Timer.ElapsedMilliseconds.ToString("0000") + " ");
}
Console.ForegroundColor = ConsoleColor.White;
this.Write("> ");
var cmd = this.ReadLine();
// support for multiline command
if (cmd.StartsWith("/"))
{
cmd = cmd.Substring(1);
while (!cmd.EndsWith("/"))
{
if (this.Timer.IsRunning)
{
this.Write(" ");
}
Console.ForegroundColor = ConsoleColor.White;
this.Write("| ");
var line = this.ReadLine();
cmd += Environment.NewLine + line;
}
cmd = cmd.Substring(0, cmd.Length - 1);
}
cmd = cmd.Trim();
this.History.Add(cmd);
if (this.Timer.IsRunning)
{
this.Timer.Reset();
this.Timer.Start();
}
return cmd.Trim();
}
/// <summary>
/// Read a line from queue or user
/// </summary>
private string ReadLine()
{
Console.ForegroundColor = ConsoleColor.Gray;
if (this.Queue.Count > 0)
{
var cmd = this.Queue.Dequeue();
this.Write(cmd + Environment.NewLine);
return cmd;
}
else
{
if (this.AutoExit) return "exit";
var cmd = Console.ReadLine();
if (this.OnWrite != null)
{
this.OnWrite(cmd + Environment.NewLine);
}
return cmd;
}
}
private void Write(string text)
{
Console.Write(text);
if (this.OnWrite != null)
{
this.OnWrite(text);
}
}
}
}