This repository was archived by the owner on Apr 24, 2023. It is now read-only.
forked from daveaglick/Scripty
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScriptyTask.cs
More file actions
282 lines (244 loc) · 10.3 KB
/
ScriptyTask.cs
File metadata and controls
282 lines (244 loc) · 10.3 KB
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Newtonsoft.Json;
namespace Scripty.MsBuild
{
public class ScriptyTask : Microsoft.Build.Utilities.Task
{
private readonly List<ITaskItem> _noneFiles = new List<ITaskItem>();
private readonly List<ITaskItem> _compileFiles = new List<ITaskItem>();
private readonly List<ITaskItem> _contentFiles = new List<ITaskItem>();
private readonly List<ITaskItem> _embeddedResourceFiles = new List<ITaskItem>();
[Required]
public string ProjectFilePath { get; set; }
public string SolutionFilePath { get; set; }
public string ScriptyExecutable { get; set; }
public string CustomProperties { get; set; }
public ITaskItem[] ScriptFiles { get; set; }
[Output]
public ITaskItem[] NoneFiles => _noneFiles.ToArray();
[Output]
public ITaskItem[] CompileFiles => _compileFiles.ToArray();
[Output]
public ITaskItem[] ContentFiles => _contentFiles.ToArray();
[Output]
public ITaskItem[] EmbeddedResourceFiles => _embeddedResourceFiles.ToArray();
public override bool Execute()
{
if (ScriptFiles == null || ScriptFiles.Length == 0)
{
return true;
}
if (string.IsNullOrEmpty(ProjectFilePath))
{
Log.LogError("A project file is required");
return false;
}
if (!Path.IsPathRooted(ProjectFilePath))
{
Log.LogError("The project file path must be absolute");
return false;
}
if (string.IsNullOrEmpty(ScriptyExecutable))
{
ScriptyExecutable = Path.Combine(Path.GetDirectoryName(typeof(ScriptyTask).Assembly.Location), "Scripty.exe");
}
if (!File.Exists(ScriptyExecutable))
{
Log.LogError($"Scripty executable not found at '{ScriptyExecutable}'.");
return false;
}
// Kick off the evaluation process, which must be done in a seperate process space
// otherwise MSBuild complains when we construct the Roslyn workspace project since
// it uses MSBuild to figure out what the project contains and MSBuild only supports
// one build per process
Log.LogMessage("Starting out-of-process script evaluation...");
List<string> outputData = new List<string>();
List<string> errorData = new List<string>();
Process process = new Process();
process.StartInfo.FileName = ScriptyExecutable;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.OutputDataReceived += (s, e) => outputData.Add(e.Data);
process.ErrorDataReceived += (s, e) => errorData.Add(e.Data);
process.Start();
// Create and send the settings
string settingsJson = GetSettingsJson();
process.StandardInput.Write(settingsJson);
process.StandardInput.Flush();
process.StandardInput.Close();
// Wait for the process to exit
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
var messages = errorData.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Split(new[] { '|' }, 2))
.Where(x => x.Length == 2)
.Select(x => new { MessageType = (MessageType)Enum.Parse(typeof(MessageType), x[0]), Message = x[1] })
.ToArray();
// Report any errors
foreach (var message in messages)
{
switch (message.MessageType)
{
case MessageType.Info:
Log.LogMessage(MessageImportance.High, message.Message);
break;
case MessageType.Warning:
Log.LogWarning(message.Message);
break;
case MessageType.Error:
Log.LogError(message.Message);
break;
}
}
if (process.ExitCode == 0)
{
Log.LogMessage("Finished script evaluation");
}
else
{
Log.LogError("Got non-zero exit code from script evaluation: " + process.ExitCode);
}
if (messages.Where(m => m.MessageType == MessageType.Error).Any())
{
return false;
}
// Add the compile files
List<Tuple<BuildAction, string>> outputFiles = outputData
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Split('|'))
.Where(x => x.Length == 2 && !string.IsNullOrWhiteSpace(x[0]) && !string.IsNullOrWhiteSpace(x[1]))
.Select(x =>
{
BuildAction buildAction;
if (!Enum.TryParse(x[0], out buildAction))
{
buildAction = BuildAction.GenerateOnly;
}
return new Tuple<BuildAction, string>(buildAction, x[1]);
})
.Where(x => x.Item1 != BuildAction.GenerateOnly)
.ToList();
Log.LogMessage("Output file count: " + outputFiles.Count);
_noneFiles.AddRange(outputFiles
.Where(x => x.Item1 == BuildAction.None)
.Select(x =>
{
TaskItem taskItem = new TaskItem(x.Item2);
taskItem.SetMetadata("AutoGen", "true");
return taskItem;
}));
_compileFiles.AddRange(outputFiles
.Where(x => x.Item1 == BuildAction.Compile)
.Select(x =>
{
TaskItem taskItem = new TaskItem(x.Item2);
taskItem.SetMetadata("AutoGen", "true");
return taskItem;
}));
_contentFiles.AddRange(outputFiles
.Where(x => x.Item1 == BuildAction.Content)
.Select(x =>
{
TaskItem taskItem = new TaskItem(x.Item2);
taskItem.SetMetadata("AutoGen", "true");
return taskItem;
}));
_embeddedResourceFiles.AddRange(outputFiles
.Where(x => x.Item1 == BuildAction.EmbeddedResource)
.Select(x =>
{
TaskItem taskItem = new TaskItem(x.Item2);
taskItem.SetMetadata("AutoGen", "true");
return taskItem;
}));
return !Log.HasLoggedErrors;
}
private string GetSettingsJson()
{
Settings settings = new Settings
{
MessagesEnabled = true,
ProjectFilePath = ProjectFilePath,
Properties = GetMsBuildProperties(),
ScriptFilePaths = ScriptFiles
.Select(x => x.GetMetadata("FullPath"))
.Where(x => !string.IsNullOrEmpty(x))
.Distinct()
.ToList(),
SolutionFilePath = SolutionFilePath?.Contains("*Undefined*") == true ? null : SolutionFilePath,
CustomProperties = GetCustomProperties()
};
return JsonConvert.SerializeObject(settings);
}
private IDictionary<string, string> GetCustomProperties()
{
if (CustomProperties == null)
return null;
var result = new Dictionary<string, string>();
var parts = Utils.AsList(CustomProperties, new char[] { ';', '=' });
if (parts.Count % 2 != 0)
{
throw new Exception("Invalid CustomProperties");
}
for (int i = 0; i < parts.Count; i += 2)
{
var key = parts[i];
var value = parts[i + 1];
result[key] = value;
}
return result;
}
private IDictionary<string, string> GetMsBuildProperties()
{
// We need to use reflection to get
// the build properties out of MSBuild.
try
{
int version = BuildEngine.GetType().Assembly.GetName().Version.Major;
// The name of the field that stores the IBuildComponentHost changed in MSBuild 14.
object host = BuildEngine.GetType().InvokeMember(
(version >= 14) ? "_host" : "host",
BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance,
null,
BuildEngine,
new object[] { }
);
object buildParameters = host.GetType().GetInterface("IBuildComponentHost").InvokeMember(
"BuildParameters",
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
null,
host,
new object[] { }
);
object globalProperties = buildParameters.GetType().InvokeMember(
"GlobalProperties",
BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance,
null,
buildParameters,
new object[] { }
);
return (IDictionary<string, string>)globalProperties;
}
catch (Exception ex)
{
Log.LogWarning("Could not get global properties from MSBuild: " + ex.Message);
return null;
}
}
}
}