Debian Codegraph @

modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs

raw symbols SCIP
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Reflection;
5 using System.Text;
6 using System.Threading.Tasks;
7 using GodotTools.IdeMessaging.Requests;
8 using Newtonsoft.Json;
9
10 namespace GodotTools.IdeMessaging.CLI
11 {
12 internal static class Program
13 {
14 private static readonly ILogger Logger = new CustomLogger();
15
16 public static int Main(string[] args)
17 {
18 try
19 {
20 var mainTask = StartAsync(args, Console.OpenStandardInput(), Console.OpenStandardOutput());
21 mainTask.Wait();
22 return mainTask.Result;
23 }
24 catch (Exception ex)
25 {
26 Logger.LogError("Unhandled exception: ", ex);
27 return 1;
28 }
29 }
30
31 private static async Task<int> StartAsync(string[] args, Stream inputStream, Stream outputStream)
32 {
33 var inputReader = new StreamReader(inputStream, Encoding.UTF8);
34 var outputWriter = new StreamWriter(outputStream, Encoding.UTF8);
35
36 try
37 {
38 if (args.Length == 0)
39 {
40 Logger.LogError("Expected at least 1 argument");
41 return 1;
42 }
43
44 string godotProjectDir = args[0];
45
46 if (!Directory.Exists(godotProjectDir))
47 {
48 Logger.LogError($"The specified Godot project directory does not exist: {godotProjectDir}");
49 return 1;
50 }
51
52 var forwarder = new ForwarderMessageHandler(outputWriter);
53
54 using (var fwdClient = new Client("VisualStudioCode", godotProjectDir, forwarder, Logger))
55 {
56 fwdClient.Start();
57
58 // ReSharper disable AccessToDisposedClosure
59 fwdClient.Connected += async () => await forwarder.WriteLineToOutput("Event=Connected");
60 fwdClient.Disconnected += async () => await forwarder.WriteLineToOutput("Event=Disconnected");
61 // ReSharper restore AccessToDisposedClosure
62
63 // TODO: Await connected with timeout
64
65 while (!fwdClient.IsDisposed)
66 {
67 string? firstLine = await inputReader.ReadLineAsync();
68
69 if (firstLine == null || firstLine == "QUIT")
70 goto ExitMainLoop;
71
72 string messageId = firstLine;
73
74 string? messageArgcLine = await inputReader.ReadLineAsync();
75
76 if (messageArgcLine == null)
77 {
78 Logger.LogInfo("EOF when expecting argument count");
79 goto ExitMainLoop;
80 }
81
82 if (!int.TryParse(messageArgcLine, out int messageArgc))
83 {
84 Logger.LogError("Received invalid line for argument count: " + firstLine);
85 continue;
86 }
87
88 var body = new StringBuilder();
89
90 for (int i = 0; i < messageArgc; i++)
91 {
92 string? bodyLine = await inputReader.ReadLineAsync();
93
94 if (bodyLine == null)
95 {
96 Logger.LogInfo($"EOF when expecting body line #{i + 1}");
97 goto ExitMainLoop;
98 }
99
100 body.AppendLine(bodyLine);
101 }
102
103 var response = await SendRequest(fwdClient, messageId, new MessageContent(MessageStatus.Ok, body.ToString()));
104
105 if (response == null)
106 {
107 Logger.LogError($"Failed to write message to the server: {messageId}");
108 }
109 else
110 {
111 var content = new MessageContent(response.Status, JsonConvert.SerializeObject(response));
112 await forwarder.WriteResponseToOutput(messageId, content);
113 }
114 }
115
116 ExitMainLoop:
117 await forwarder.WriteLineToOutput("Event=Quit");
118 }
119
120 return 0;
121 }
122 catch (Exception e)
123 {
124 Logger.LogError("Unhandled exception", e);
125 return 1;
126 }
127 }
128
129 private static async Task<Response?> SendRequest(Client client, string id, MessageContent content)
130 {
131 var handlers = new Dictionary<string, Func<Task<Response?>>>
132 {
133 [PlayRequest.Id] = async () =>
134 {
135 var request = JsonConvert.DeserializeObject<PlayRequest>(content.Body);
136 return await client.SendRequest<PlayResponse>(request!);
137 },
138 [DebugPlayRequest.Id] = async () =>
139 {
140 var request = JsonConvert.DeserializeObject<DebugPlayRequest>(content.Body);
141 return await client.SendRequest<DebugPlayResponse>(request!);
142 },
143 [ReloadScriptsRequest.Id] = async () =>
144 {
145 var request = JsonConvert.DeserializeObject<ReloadScriptsRequest>(content.Body);
146 return await client.SendRequest<ReloadScriptsResponse>(request!);
147 },
148 [CodeCompletionRequest.Id] = async () =>
149 {
150 var request = JsonConvert.DeserializeObject<CodeCompletionRequest>(content.Body);
151 return await client.SendRequest<CodeCompletionResponse>(request!);
152 }
153 };
154
155 if (handlers.TryGetValue(id, out var handler))
156 return await handler();
157
158 Console.WriteLine("INVALID REQUEST");
159 return null;
160 }
161
162 private class CustomLogger : ILogger
163 {
164 private static string ThisAppPath => Assembly.GetExecutingAssembly().Location;
165 private static string ThisAppPathWithoutExtension => Path.ChangeExtension(ThisAppPath, null);
166
167 private static readonly string LogPath = $"{ThisAppPathWithoutExtension}.log";
168
169 private static StreamWriter NewWriter() => new StreamWriter(LogPath, append: true, encoding: Encoding.UTF8);
170
171 private static void Log(StreamWriter writer, string message)
172 {
173 writer.WriteLine($"{DateTime.Now:HH:mm:ss.ffffff}: {message}");
174 }
175
176 public void LogDebug(string message)
177 {
178 using (var writer = NewWriter())
179 {
180 Log(writer, "DEBUG: " + message);
181 }
182 }
183
184 public void LogInfo(string message)
185 {
186 using (var writer = NewWriter())
187 {
188 Log(writer, "INFO: " + message);
189 }
190 }
191
192 public void LogWarning(string message)
193 {
194 using (var writer = NewWriter())
195 {
196 Log(writer, "WARN: " + message);
197 }
198 }
199
200 public void LogError(string message)
201 {
202 using (var writer = NewWriter())
203 {
204 Log(writer, "ERROR: " + message);
205 }
206 }
207
208 public void LogError(string message, Exception e)
209 {
210 using (var writer = NewWriter())
211 {
212 Log(writer, "EXCEPTION: " + message + '\n' + e);
213 }
214 }
215 }
216 }
217 }