-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathEventManager.cs
More file actions
423 lines (370 loc) · 13.7 KB
/
EventManager.cs
File metadata and controls
423 lines (370 loc) · 13.7 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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*!
* Copyright (c) 2013 Denis Kuzmin <x-3F@outlook.com> github/3F
* Copyright (c) vsSolutionBuildEvent contributors https://github.com/3F/vsSolutionBuildEvent/graphs/contributors
* This component (part of vsSolutionBuildEvent) is licensed under the MIT License (MIT).
* See accompanying License.txt file or visit https://github.com/3F/vsSolutionBuildEvent
*/
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using net.r_eg.MvsSln;
using net.r_eg.vsSBE.Bridge.CoreCommand;
using net.r_eg.vsSBE.Provider;
using BuildType = net.r_eg.vsSBE.Bridge.BuildType;
namespace net.r_eg.vsSBE.CI.MSBuild
{
public class EventManager: Logger, ILogger
{
/// <summary>
/// Full path to solution file
/// </summary>
public string SolutionFile
{
get;
private set;
}
/// <summary>
/// Our the vsSolutionBuildEvent library
/// </summary>
public ILibrary library;
/// <summary>
/// Internal logging
/// </summary>
internal ILog log;
/// <summary>
/// Initializer of library
/// </summary>
internal Initializer initializer;
/// <summary>
/// Specified type of build action
/// </summary>
protected volatile BuildType buildType = BuildType.Common;
/// <summary>
/// About projects by ident
/// </summary>
protected IDictionary<int, Project> projects = new Dictionary<int, Project>();
/// <summary>
/// All received CoreCommand from library.
/// </summary>
protected Stack<ICoreCommand> receivedCommands = new Stack<ICoreCommand>();
/// <summary>
/// List of started targets and their Pre/Post states.
/// </summary>
private ConcurrentDictionary<int, bool> ptargets = new ConcurrentDictionary<int, bool>();
/// <summary>
/// Reserved for future use with IVsSolutionEvents
/// </summary>
private readonly object pUnkReserved = new object();
/// <summary>
/// To abort all processes as soon as possible
/// </summary>
private volatile bool abort = false;
private readonly object _sync = new object();
/// <summary>
/// Initializer of the Build.Framework.ILogger objects.
/// Subscribes to specific events etc.
/// </summary>
/// <param name="evt"></param>
public override void Initialize(IEventSource evt)
{
log = new Log(Verbosity);
initializer = new Initializer(Parameters, log);
if(!log.IsDiagnostic) {
log.info($"set {Log.DIAG_KEY}= true to enable diagnostic mode.");
}
// load with properties by default
library = initializer.load();
setPropertiesByDefault();
attachCoreCommandListener(library);
library.Event.solutionOpened(pUnkReserved, 0);
// bring song
evt.TargetStarted += onTargetStarted;
evt.ProjectStarted += onProjectStarted;
evt.AnyEventRaised += onAnyEventRaised;
evt.ErrorRaised += onErrorRaised;
evt.WarningRaised += onWarningRaised;
evt.BuildStarted += onBuildStarted;
evt.BuildFinished += onBuildFinished;
}
public override void Shutdown()
{
if(library != null) {
library.Event.solutionClosed(pUnkReserved);
detachCoreCommandListener(library);
}
}
protected void onProjectStarted(object sender, ProjectStartedEventArgs e)
{
termination(); // This is first place where we can use it
if(e.ProjectFile.EndsWith(".metaproj", StringComparison.InvariantCultureIgnoreCase)
|| e.ProjectFile.EndsWith(".user", StringComparison.InvariantCultureIgnoreCase))
{
debug($"ignored '{e.ProjectFile}'");
return;
}
if(projects.ContainsKey(e.ProjectId)) {
// already pushed
return;
}
//updateBuildType(e.TargetNames);
if(e.Properties == null) {
debug("onProjectStarted: e.Properties is null :: '{0}' ({1})", e.ProjectFile, e.Message);
return;
}
var properties = e.Properties.OfType<DictionaryEntry>().ToDictionary(k => k.Key, v => v.Value.ToString());
if(properties.ContainsKey(PropertyNames.PRJ_NAME))
{
projects[e.ProjectId] = new Project() {
Name = properties[PropertyNames.PRJ_NAME],
File = e.ProjectFile,
Properties = properties
};
}
}
protected void onTargetStarted(object sender, TargetStartedEventArgs e)
{
int pid = e.BuildEventContext.ProjectInstanceId;
if(!projects.ContainsKey(pid)) {
return;
}
// the PreBuildEvent & PostBuildEvent should be only for condition '$(PreBuildEvent)'!='' ...
switch(e.TargetName)
{
case "BeforeBuild":
case "BeforeRebuild":
case "BeforeClean":
{
if(!ptargets.ContainsKey(pid)) {
ptargets[pid] = false; //pre
library.Event.onProjectPre(projects[pid].Name);
}
break;
}
case "AfterBuild":
case "AfterRebuild":
case "AfterClean":
{
if(!ptargets.ContainsKey(pid) || !ptargets[pid]) {
ptargets[pid] = true; //post
library.Event.onProjectPost(projects[pid].Name, projects[pid].HasErrors ? 0 : 1);
}
break;
}
}
}
protected void onWarningRaised(object sender, BuildWarningEventArgs e)
{
if(library != null) {
library.Build.onBuildRaw(formatEW("warning", e.Code, e.Message, e.File, e.LineNumber));
}
}
protected void onErrorRaised(object sender, BuildErrorEventArgs e)
{
if(projects.ContainsKey(e.BuildEventContext.ProjectInstanceId)) {
projects[e.BuildEventContext.ProjectInstanceId].HasErrors = true;
}
if(library != null) {
library.Build.onBuildRaw(formatEW("error", e.Code, e.Message, e.File, e.LineNumber));
}
}
protected void onPre(string targets)
{
updateBuildType(targets);
int pfCancelUpdate = 0;
library.Event.onPre(ref pfCancelUpdate);
}
/// <summary>
/// Note with msbuild:
/// Be careful - the onBuildStarted(i.e. all before onTargetStarted) is not safe for any unhandled exceptions!
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void onBuildStarted(object sender, BuildStartedEventArgs e)
{
try {
ptargets.Clear();
// yes, we're ready
onPre(initializer.Properties.Targets);
}
catch(Exception ex) {
debug("Error onBuildStarted: '{0}'", ex.Message);
abort = true;
}
}
protected void onBuildFinished(object sender, BuildFinishedEventArgs e)
{
if(library == null) {
return;
}
if(!e.Succeeded) {
library.Event.onCancel();
}
library.Event.onPost((e.Succeeded ? 1 : 0), 0, 0);
}
/// <summary>
/// see also: MessageRaised or StatusEventRaised
/// </summary>
protected void onAnyEventRaised(object sender, BuildEventArgs e)
{
library?.Build.onBuildRaw
(
e.Message ?? $" #@ {e.ThreadId}:{e.BuildEventContext?.BuildRequestId} , {e.BuildEventContext}"
);
}
/// <summary>
/// Handler of core commands.
/// </summary>
/// <param name="sender"></param>
/// <param name="c"></param>
protected void command(object sender, CoreCommandArgs c)
{
switch(c.Type)
{
case CoreCommandType.AbortCommand: {
abortCommand(c);
break;
}
case CoreCommandType.BuildCancel: {
abort = true;
break;
}
case CoreCommandType.Nop: {
break;
}
case CoreCommandType.RawCommand: {
rawCommand(c);
break;
}
}
receivedCommands.Push(c);
}
/// <summary>
/// Aborts latest command if it's possible
/// </summary>
/// <param name="c"></param>
protected void abortCommand(ICoreCommand c)
{
if(receivedCommands.Count < 1) {
return;
}
ICoreCommand last = receivedCommands.Peek();
if(last.Type == CoreCommandType.BuildCancel) {
abort = false;
}
}
protected void rawCommand(ICoreCommand c)
{
if(c.Args.Length < 1) {
msg("RawCommand is incorrect or broken.");
return;
}
switch(c.Args[0].ToString()) {
case "property.set": {
setProperty(c.Args[1].ToString(), c.Args[2].ToString());
return;
}
case "property.del": {
setProperty(c.Args[1].ToString(), null);
return;
}
}
}
protected bool attachCoreCommandListener(ILibrary library)
{
if(library == null) {
return false;
}
lock(_sync) {
detachCoreCommandListener(library);
library.EntryPoint.CoreCommand += command;
}
return true;
}
protected bool detachCoreCommandListener(ILibrary library)
{
if(library == null) {
return false;
}
lock(_sync) {
library.EntryPoint.CoreCommand -= command;
}
return true;
}
/// <summary>
/// Updates the type by target name if it exists in BuildType list
/// https://msdn.microsoft.com/en-us/library/vstudio/ms164311.aspx
/// </summary>
/// <param name="targets">each target separately or with a semicolon if this is a multiple targets</param>
protected void updateBuildType(string targets)
{
foreach(string target in targets.Split(';'))
{
if(Enum.IsDefined(typeof(BuildType), target.Trim()))
{
buildType = (BuildType)Enum.Parse(typeof(BuildType), target);
library.Build.updateBuildType(buildType);
debug("updateBuildType: '{0}' from - '{1}'", buildType, targets);
return; // use as 'or' for a multiple targets
}
}
}
/// <summary>
/// Logic of termination the msbuild job
/// </summary>
protected void termination()
{
if(!abort) {
return;
}
//TODO: Another way ? fix me
throw new LoggerException(
String.Format(
"The build has been canceled{0}.",
(receivedCommands.Count < 1)? "" : " by user script"
));
}
protected virtual void setProperty(string name, string value)
{
debug("setProperty '{0}' = `{1}`", name, value);
Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.Process);
}
/// <summary>
/// Note:
/// The main core is already provides properties by default,
/// but all this are not available for msbuild targets from CIM.
/// Thus, we need also provide this via current environment etc.
///
/// FIXME:
/// </summary>
protected void setPropertiesByDefault()
{
setProperty("vsSolutionBuildEvent", library.Version.Number.ToString()); //optional
setProperty("vssbeCIM", Version.S_NUM_REV);
}
/// <summary>
/// Specification of this format: http://msdn.microsoft.com/en-us/library/yxkt8b26.aspx
/// </summary>
/// <param name="type">Type of message</param>
/// <param name="code">code####</param>
/// <param name="msg">Localizable string</param>
/// <param name="file">Filename</param>
/// <param name="line">Line</param>
/// <returns></returns>
protected virtual string formatEW(string type, string code, string msg, string file, int line)
{
return $"{file}({line}): {type} {code}: {msg}";
}
private void msg(string data, params object[] args)
{
log.info(data, args);
}
private void debug(string data, params object[] args)
{
log.debug(data, args);
}
}
}