summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/Program.cs
blob: 4db71500da156e0776fb21695e84a05780e17949 (plain)
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using GodotTools.IdeMessaging.Requests;
using Newtonsoft.Json;

namespace GodotTools.IdeMessaging.CLI
{
    internal static class Program
    {
        private static readonly ILogger Logger = new CustomLogger();

        public static int Main(string[] args)
        {
            try
            {
                var mainTask = StartAsync(args, Console.OpenStandardInput(), Console.OpenStandardOutput());
                mainTask.Wait();
                return mainTask.Result;
            }
            catch (Exception ex)
            {
                Logger.LogError("Unhandled exception: ", ex);
                return 1;
            }
        }

        private static async Task<int> StartAsync(string[] args, Stream inputStream, Stream outputStream)
        {
            var inputReader = new StreamReader(inputStream, Encoding.UTF8);
            var outputWriter = new StreamWriter(outputStream, Encoding.UTF8);

            try
            {
                if (args.Length == 0)
                {
                    Logger.LogError("Expected at least 1 argument");
                    return 1;
                }

                string godotProjectDir = args[0];

                if (!Directory.Exists(godotProjectDir))
                {
                    Logger.LogError($"The specified Godot project directory does not exist: {godotProjectDir}");
                    return 1;
                }

                var forwarder = new ForwarderMessageHandler(outputWriter);

                using (var fwdClient = new Client("VisualStudioCode", godotProjectDir, forwarder, Logger))
                {
                    fwdClient.Start();

                    // ReSharper disable AccessToDisposedClosure
                    fwdClient.Connected += async () => await forwarder.WriteLineToOutput("Event=Connected");
                    fwdClient.Disconnected += async () => await forwarder.WriteLineToOutput("Event=Disconnected");
                    // ReSharper restore AccessToDisposedClosure

                    // TODO: Await connected with timeout

                    while (!fwdClient.IsDisposed)
                    {
                        string firstLine = await inputReader.ReadLineAsync();

                        if (firstLine == null || firstLine == "QUIT")
                            goto ExitMainLoop;

                        string messageId = firstLine;

                        string messageArgcLine = await inputReader.ReadLineAsync();

                        if (messageArgcLine == null)
                        {
                            Logger.LogInfo("EOF when expecting argument count");
                            goto ExitMainLoop;
                        }

                        if (!int.TryParse(messageArgcLine, out int messageArgc))
                        {
                            Logger.LogError("Received invalid line for argument count: " + firstLine);
                            continue;
                        }

                        var body = new StringBuilder();

                        for (int i = 0; i < messageArgc; i++)
                        {
                            string bodyLine = await inputReader.ReadLineAsync();

                            if (bodyLine == null)
                            {
                                Logger.LogInfo($"EOF when expecting body line #{i + 1}");
                                goto ExitMainLoop;
                            }

                            body.AppendLine(bodyLine);
                        }

                        var response = await SendRequest(fwdClient, messageId, new MessageContent(MessageStatus.Ok, body.ToString()));

                        if (response == null)
                        {
                            Logger.LogError($"Failed to write message to the server: {messageId}");
                        }
                        else
                        {
                            var content = new MessageContent(response.Status, JsonConvert.SerializeObject(response));
                            await forwarder.WriteResponseToOutput(messageId, content);
                        }
                    }

                    ExitMainLoop:

                    await forwarder.WriteLineToOutput("Event=Quit");
                }

                return 0;
            }
            catch (Exception e)
            {
                Logger.LogError("Unhandled exception", e);
                return 1;
            }
        }

        private static async Task<Response> SendRequest(Client client, string id, MessageContent content)
        {
            var handlers = new Dictionary<string, Func<Task<Response>>>
            {
                [PlayRequest.Id] = async () =>
                {
                    var request = JsonConvert.DeserializeObject<PlayRequest>(content.Body);
                    return await client.SendRequest<PlayResponse>(request);
                },
                [DebugPlayRequest.Id] = async () =>
                {
                    var request = JsonConvert.DeserializeObject<DebugPlayRequest>(content.Body);
                    return await client.SendRequest<DebugPlayResponse>(request);
                },
                [ReloadScriptsRequest.Id] = async () =>
                {
                    var request = JsonConvert.DeserializeObject<ReloadScriptsRequest>(content.Body);
                    return await client.SendRequest<ReloadScriptsResponse>(request);
                },
                [CodeCompletionRequest.Id] = async () =>
                {
                    var request = JsonConvert.DeserializeObject<CodeCompletionRequest>(content.Body);
                    return await client.SendRequest<CodeCompletionResponse>(request);
                }
            };

            if (handlers.TryGetValue(id, out var handler))
                return await handler();

            Console.WriteLine("INVALID REQUEST");
            return null;
        }

        private class CustomLogger : ILogger
        {
            private static string ThisAppPath => Assembly.GetExecutingAssembly().Location;
            private static string ThisAppPathWithoutExtension => Path.ChangeExtension(ThisAppPath, null);

            private static readonly string LogPath = $"{ThisAppPathWithoutExtension}.log";

            private static StreamWriter NewWriter() => new StreamWriter(LogPath, append: true, encoding: Encoding.UTF8);

            private static void Log(StreamWriter writer, string message)
            {
                writer.WriteLine($"{DateTime.Now:HH:mm:ss.ffffff}: {message}");
            }

            public void LogDebug(string message)
            {
                using (var writer = NewWriter())
                {
                    Log(writer, "DEBUG: " + message);
                }
            }

            public void LogInfo(string message)
            {
                using (var writer = NewWriter())
                {
                    Log(writer, "INFO: " + message);
                }
            }

            public void LogWarning(string message)
            {
                using (var writer = NewWriter())
                {
                    Log(writer, "WARN: " + message);
                }
            }

            public void LogError(string message)
            {
                using (var writer = NewWriter())
                {
                    Log(writer, "ERROR: " + message);
                }
            }

            public void LogError(string message, Exception e)
            {
                using (var writer = NewWriter())
                {
                    Log(writer, "EXCEPTION: " + message + '\n' + e);
                }
            }
        }
    }
}