summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotSharpTools/Build/BuildSystem.cs
blob: 256e64dddef0b1cabeace718f6c47925c9053ccd (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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.Build.Framework;

namespace GodotSharpTools.Build
{
    public class BuildInstance : IDisposable
    {
        [MethodImpl(MethodImplOptions.InternalCall)]
        internal extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode);

        [MethodImpl(MethodImplOptions.InternalCall)]
        internal extern static string godot_icall_BuildInstance_get_MSBuildPath();

        private static string MSBuildPath
        {
            get { return godot_icall_BuildInstance_get_MSBuildPath(); }
        }

        private string solution;
        private string config;

        private Process process;

        private int exitCode;
        public int ExitCode { get { return exitCode; } }

        public bool IsRunning { get { return process != null && !process.HasExited; } }

        public BuildInstance(string solution, string config)
        {
            this.solution = solution;
            this.config = config;
        }

        public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
        {
            string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);

            ProcessStartInfo startInfo = new ProcessStartInfo(MSBuildPath, compilerArgs);

            // No console output, thanks
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;

            // Needed when running from Developer Command Prompt for VS
            RemovePlatformVariable(startInfo.EnvironmentVariables);

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.WaitForExit();

                exitCode = process.ExitCode;
            }

            return true;
        }

        public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
        {
            if (process != null)
                throw new InvalidOperationException("Already in use");

            string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);

            ProcessStartInfo startInfo = new ProcessStartInfo("msbuild", compilerArgs);

            // No console output, thanks
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;

            // Needed when running from Developer Command Prompt for VS
            RemovePlatformVariable(startInfo.EnvironmentVariables);

            process = new Process();
            process.StartInfo = startInfo;
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(BuildProcess_Exited);

            process.Start();

            return true;
        }

        private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties)
        {
            string arguments = string.Format("{0} /v:normal /t:Build /p:{1} /l:{2},{3};{4}",
                solution,
                "Configuration=" + config,
                typeof(GodotBuildLogger).FullName,
                loggerAssemblyPath,
                loggerOutputDir
            );

            if (customProperties != null)
            {
                foreach (string customProperty in customProperties)
                {
                    arguments += " /p:" + customProperty;
                }
            }

            return arguments;
        }

        private void RemovePlatformVariable(StringDictionary environmentVariables)
        {
            // EnvironmentVariables is case sensitive? Seriously?

            List<string> platformEnvironmentVariables = new List<string>();

            foreach (string env in environmentVariables.Keys)
            {
                if (env.ToUpper() == "PLATFORM")
                    platformEnvironmentVariables.Add(env);
            }

            foreach (string env in platformEnvironmentVariables)
                environmentVariables.Remove(env);
        }

        private void BuildProcess_Exited(object sender, System.EventArgs e)
        {
            exitCode = process.ExitCode;

            godot_icall_BuildInstance_ExitCallback(solution, config, exitCode);

            Dispose();
        }

        public void Dispose()
        {
            if (process != null)
            {
                process.Dispose();
                process = null;
            }
        }
    }

    public class GodotBuildLogger : ILogger
    {
        public string Parameters { get; set; }
        public LoggerVerbosity Verbosity { get; set; }

        public void Initialize(IEventSource eventSource)
        {
            if (null == Parameters)
                throw new LoggerException("Log directory was not set.");

            string[] parameters = Parameters.Split(';');

            string logDir = parameters[0];

            if (String.IsNullOrEmpty(logDir))
                throw new LoggerException("Log directory was not set.");

            if (parameters.Length > 1)
                throw new LoggerException("Too many parameters passed.");

            string logFile = Path.Combine(logDir, "msbuild_log.txt");
            string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");

            try
            {
                if (!Directory.Exists(logDir))
                    Directory.CreateDirectory(logDir);

                this.logStreamWriter = new StreamWriter(logFile);
                this.issuesStreamWriter = new StreamWriter(issuesFile);
            }
            catch (Exception ex)
            {
                if
                (
                    ex is UnauthorizedAccessException
                    || ex is ArgumentNullException
                    || ex is PathTooLongException
                    || ex is DirectoryNotFoundException
                    || ex is NotSupportedException
                    || ex is ArgumentException
                    || ex is SecurityException
                    || ex is IOException
                )
                {
                    throw new LoggerException("Failed to create log file: " + ex.Message);
                }
                else
                {
                    // Unexpected failure
                    throw;
                }
            }

            eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
            eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted);
            eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised);
            eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
            eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
            eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
        }

        void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
        {
            string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message);

            if (e.ProjectFile.Length > 0)
                line += string.Format(" [{0}]", e.ProjectFile);

            WriteLine(line);

            string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}",
                                    e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
                                    e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape());
            issuesStreamWriter.WriteLine(errorLine);
        }

        void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
        {
            string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile);

            if (e.ProjectFile != null && e.ProjectFile.Length > 0)
                line += string.Format(" [{0}]", e.ProjectFile);

            WriteLine(line);

            string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}",
                                    e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
                                    e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty);
            issuesStreamWriter.WriteLine(warningLine);
        }

        void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
        {
            // BuildMessageEventArgs adds Importance to BuildEventArgs
            // Let's take account of the verbosity setting we've been passed in deciding whether to log the message
            if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal))
                || (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal))
                || (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
                )
            {
                WriteLineWithSenderAndMessage(String.Empty, e);
            }
        }

        void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
        {
            // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
            // To keep this log clean, this logger will ignore these events.
        }

        void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
        {
            WriteLine(e.Message);
            indent++;
        }

        void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
        {
            indent--;
            WriteLine(e.Message);
        }

        /// <summary>
        /// Write a line to the log, adding the SenderName
        /// </summary>
        private void WriteLineWithSender(string line, BuildEventArgs e)
        {
            if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
            {
                // Well, if the sender name is MSBuild, let's leave it out for prettiness
                WriteLine(line);
            }
            else
            {
                WriteLine(e.SenderName + ": " + line);
            }
        }

        /// <summary>
        /// Write a line to the log, adding the SenderName and Message
        /// (these parameters are on all MSBuild event argument objects)
        /// </summary>
        private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
        {
            if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
            {
                // Well, if the sender name is MSBuild, let's leave it out for prettiness
                WriteLine(line + e.Message);
            }
            else
            {
                WriteLine(e.SenderName + ": " + line + e.Message);
            }
        }

        private void WriteLine(string line)
        {
            for (int i = indent; i > 0; i--)
            {
                logStreamWriter.Write("\t");
            }
            logStreamWriter.WriteLine(line);
        }

        public void Shutdown()
        {
            logStreamWriter.Close();
            issuesStreamWriter.Close();
        }

        public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
        {
            return this.Verbosity >= checkVerbosity;
        }

        private StreamWriter logStreamWriter;
        private StreamWriter issuesStreamWriter;
        private int indent;
    }
}