BadScript 2
Loading...
Searching...
No Matches
BadTerminal.cs
Go to the documentation of this file.
2
3public class BadTerminal
4{
5 public readonly BadReplContext Context;
6
7 public string TerminalPrefix { get; set; } = "$";
8
9 private readonly List<BadTerminalCommand> m_Commands = new List<BadTerminalCommand>();
10
11 public bool IsRunning { get; private set; }
12
13 private readonly CancellationTokenSource m_Cts = new CancellationTokenSource();
23 public void RegisterCommand(BadTerminalCommand cmd) => m_Commands.Add(cmd);
24 public void Start()
25 {
26 if (IsRunning) return;
27 IsRunning = true;
28 Task.Run(() => Loop(m_Cts.Token));
29 }
30
31 public void Stop()
32 {
33 if (!IsRunning) return;
34 m_Cts.Cancel();
35 }
36
37 private void WritePrefix()
38 {
39 Context.Console.Write($"{Context.FileSystem.GetCurrentDirectory()} {TerminalPrefix} ");
40 }
41 private async Task Loop(CancellationToken ct)
42 {
43 while (!ct.IsCancellationRequested)
44 {
46 string input = await Context.Console.ReadLineAsync();
47 if (string.IsNullOrWhiteSpace(input)) continue;
48 string[] parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
49 string cmd = parts[0];
50 string[] args = parts.Skip(1).ToArray();
51 BadTerminalCommand? command = m_Commands.FirstOrDefault(c => c.Names.Contains(cmd));
52 if (command == null)
53 {
54 Context.Console.WriteLine($"Command '{cmd}' not found.");
55 continue;
56 }
57
58 try
59 {
60 await command.Run(Context, args);
61 }
62 catch (Exception e)
63 {
64 Context.Console.WriteLine($"Error: {e.Message}");
65 }
66 }
67
68 IsRunning = false;
69 }
70}
Task Run(BadReplContext context, string[] args)
readonly List< BadTerminalCommand > m_Commands
Definition BadTerminal.cs:9
void RegisterCommand(BadTerminalCommand cmd)
async Task Loop(CancellationToken ct)
readonly CancellationTokenSource m_Cts