forked from FortuneN/FineCodeCoverage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFCCEngine.cs
More file actions
402 lines (342 loc) · 16.7 KB
/
FCCEngine.cs
File metadata and controls
402 lines (342 loc) · 16.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
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using FineCodeCoverage.Core.MsTestPlatform.TestingPlatform;
using FineCodeCoverage.Core.Utilities;
using FineCodeCoverage.Engine.Cobertura;
using FineCodeCoverage.Engine.Model;
using FineCodeCoverage.Engine.MsTestPlatform;
using FineCodeCoverage.Engine.MsTestPlatform.CodeCoverage;
using FineCodeCoverage.Engine.ReportGenerator;
using FineCodeCoverage.Impl;
using FineCodeCoverage.Options;
using FineCodeCoverage.Output;
namespace FineCodeCoverage.Engine
{
internal enum ReloadCoverageStatus { Start, Done, Cancelled, Error, Initializing };
internal sealed class NewCoverageLinesMessage
{
public IFileLineCoverage CoverageLines { get; set; }
}
internal class CoverageTaskState
{
public CancellationTokenSource CancellationTokenSource { get; set; }
public Action CleanUp { get; set; }
}
internal class ReportResult
{
public IFileLineCoverage FileLineCoverage { get; set; }
public string ProcessedReport { get; set; }
public string HotspotsFile { get; set; }
public string CoberturaFile { get; set; }
}
class ReportFilesMessage
{
public string HotspotsFile { get; set; }
public string CoberturaFile { get; set; }
}
[Export(typeof(IFCCEngine))]
internal class FCCEngine : IFCCEngine,IDisposable
{
internal int InitializeWait { get; set; } = 5000;
internal const string initializationFailedMessagePrefix = "Initialization failed. Please check the following error which may be resolved by reopening visual studio which will start the initialization process again.";
private CancellationTokenSource cancellationTokenSource;
public string AppDataFolderPath { get; private set; }
private bool IsVsShutdown => disposeAwareTaskRunner.DisposalToken.IsCancellationRequested;
private readonly ICoverageUtilManager coverageUtilManager;
private readonly ICoberturaUtil coberturaUtil;
private readonly IMsCodeCoverageRunSettingsService msCodeCoverageRunSettingsService;
private readonly IMsTestPlatformUtil msTestPlatformUtil;
private readonly IReportGeneratorUtil reportGeneratorUtil;
private readonly ILogger logger;
private readonly IAppDataFolder appDataFolder;
private readonly ICoverageToolOutputManager coverageOutputManager;
internal System.Threading.Tasks.Task reloadCoverageTask;
#pragma warning disable IDE0052 // Remove unread private members
private readonly ISolutionEvents solutionEvents; // keep alive
#pragma warning restore IDE0052 // Remove unread private members
private readonly IEventAggregator eventAggregator;
private readonly IDisposeAwareTaskRunner disposeAwareTaskRunner;
private readonly ITUnitCoverageRunner tUnitCoverageRunner;
private bool disposed = false;
[ImportingConstructor]
public FCCEngine(
ICoverageUtilManager coverageUtilManager,
ICoberturaUtil coberturaUtil,
IMsTestPlatformUtil msTestPlatformUtil,
IReportGeneratorUtil reportGeneratorUtil,
ILogger logger,
IAppDataFolder appDataFolder,
ICoverageToolOutputManager coverageOutputManager,
IMsCodeCoverageRunSettingsService msCodeCoverageRunSettingsService,
ISolutionEvents solutionEvents,
IAppOptionsProvider appOptionsProvider,
IEventAggregator eventAggregator,
IDisposeAwareTaskRunner disposeAwareTaskRunner,
ITUnitCoverageRunner tUnitCoverageRunner
)
{
this.solutionEvents = solutionEvents;
this.eventAggregator = eventAggregator;
this.disposeAwareTaskRunner = disposeAwareTaskRunner;
this.tUnitCoverageRunner = tUnitCoverageRunner;
solutionEvents.AfterClosing += (s,args) => ClearUI(false);
appOptionsProvider.OptionsChanged += (appOptions) =>
{
if (!appOptions.Enabled)
{
ClearUI();
}
};
this.coverageOutputManager = coverageOutputManager;
this.coverageUtilManager = coverageUtilManager;
this.coberturaUtil = coberturaUtil;
this.msTestPlatformUtil = msTestPlatformUtil;
this.reportGeneratorUtil = reportGeneratorUtil;
this.logger = logger;
this.appDataFolder = appDataFolder;
this.msCodeCoverageRunSettingsService = msCodeCoverageRunSettingsService;
}
private void LogReloadCoverageStatus(ReloadCoverageStatus reloadCoverageStatus)
{
logger.Log(StatusMarkerProvider.Get(reloadCoverageStatus.ToString()));
}
public void Initialize(CancellationToken cancellationToken)
{
appDataFolder.Initialize(cancellationToken);
AppDataFolderPath = appDataFolder.DirectoryPath;
reportGeneratorUtil.Initialize(AppDataFolderPath, cancellationToken);
msTestPlatformUtil.Initialize(AppDataFolderPath, cancellationToken);
coverageUtilManager.Initialize(AppDataFolderPath, cancellationToken);
msCodeCoverageRunSettingsService.Initialize(AppDataFolderPath, this,cancellationToken);
tUnitCoverageRunner.Initialize(AppDataFolderPath, cancellationToken);
}
public void ClearUI(bool clearOutputWindowHistory = true)
{
ClearCoverageLines();
ClearOutputWindow(clearOutputWindowHistory);
}
private void ClearOutputWindow(bool withHistory)
{
RaiseUpdateOutputWindow(reportGeneratorUtil.BlankReport(withHistory));
}
public void StopCoverage()
{
if (cancellationTokenSource != null)
{
try
{
cancellationTokenSource.Cancel();
}
catch (ObjectDisposedException) { }
}
}
private CancellationTokenSource Reset()
{
ClearCoverageLines();
StopCoverage();
cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(disposeAwareTaskRunner.DisposalToken);
return cancellationTokenSource;
}
private async System.Threading.Tasks.Task<string[]> RunCoverageAsync(List<ICoverageProject> coverageProjects,CancellationToken vsShutdownLinkedCancellationToken)
{
// process pipeline
await PrepareCoverageProjectsAsync(coverageProjects, vsShutdownLinkedCancellationToken);
foreach (var coverageProject in coverageProjects)
{
await coverageProject.StepAsync("Run Coverage Tool", async (project) =>
{
var start = DateTime.Now;
var coverageTool = coverageUtilManager.CoverageToolName(project);
var runCoverToolMessage = $"Run {coverageTool} ({project.ProjectName})";
reportGeneratorUtil.LogCoverageProcess(runCoverToolMessage);
await coverageUtilManager.RunCoverageAsync(project, vsShutdownLinkedCancellationToken);
var duration = DateTime.Now - start;
var durationMessage = $"Completed coverage for ({coverageProject.ProjectName}) : {duration}";
logger.Log(durationMessage);
reportGeneratorUtil.LogCoverageProcess(durationMessage);
});
if (coverageProject.HasFailed)
{
var coverageStagePrefix = String.IsNullOrEmpty(coverageProject.FailureStage) ? "" : $"{coverageProject.FailureStage} ";
var failureMessage = $"{coverageProject.FailureStage}({coverageProject.ProjectName}) Failed.";
logger.Log(failureMessage, coverageProject.FailureDescription);
reportGeneratorUtil.LogCoverageProcess(failureMessage + " See the FCC Output Pane");
}
}
var passedProjects = coverageProjects.Where(p => !p.HasFailed);
return passedProjects
.Select(x => x.CoverageOutputFile)
.ToArray();
}
private void RaiseUpdateOutputWindow(string reportHtml)
{
eventAggregator.SendMessage(new NewReportMessage { Report = reportHtml });
}
private void ClearCoverageLines()
{
RaiseCoverageLines(null);
}
private void RaiseCoverageLines(IFileLineCoverage coverageLines)
{
eventAggregator.SendMessage(new NewCoverageLinesMessage { CoverageLines = coverageLines});
}
private void UpdateUI(IFileLineCoverage coverageLines, string reportHtml)
{
RaiseCoverageLines(coverageLines);
if (reportHtml == null)
{
reportHtml = reportGeneratorUtil.BlankReport(true);
}
RaiseUpdateOutputWindow(reportHtml);
}
private async System.Threading.Tasks.Task<ReportResult> RunAndProcessReportAsync(string[] coverOutputFiles, CancellationToken vsShutdownLinkedCancellationToken)
{
var reportOutputFolder = coverageOutputManager.GetReportOutputFolder();
vsShutdownLinkedCancellationToken.ThrowIfCancellationRequested();
var result = await reportGeneratorUtil.GenerateAsync(coverOutputFiles,reportOutputFolder,vsShutdownLinkedCancellationToken);
vsShutdownLinkedCancellationToken.ThrowIfCancellationRequested();
logger.Log("Processing cobertura");
var coverageLines = coberturaUtil.ProcessCoberturaXml(result.UnifiedXmlFile);
vsShutdownLinkedCancellationToken.ThrowIfCancellationRequested();
logger.Log("Processing report");
string processedReport = reportGeneratorUtil.ProcessUnifiedHtml(result.UnifiedHtml, reportOutputFolder);
return new ReportResult
{
FileLineCoverage = coverageLines,
HotspotsFile = result.HotspotsFile,
CoberturaFile = result.UnifiedXmlFile,
ProcessedReport = processedReport
};
}
private async System.Threading.Tasks.Task PrepareCoverageProjectsAsync(List<ICoverageProject> coverageProjects, CancellationToken cancellationToken)
{
foreach (var project in coverageProjects)
{
if (string.IsNullOrWhiteSpace(project.ProjectFile))
{
project.FailureDescription = $"Unsupported project type for DLL '{project.TestDllFile}'";
continue;
}
if (!project.Settings.Enabled)
{
project.FailureDescription = $"Disabled";
continue;
}
var fileSynchronizationDetails = await project.PrepareForCoverageAsync(cancellationToken);
var logs = fileSynchronizationDetails.Logs;
if (logs.Any())
{
logs.Insert(0, "File synchronization :");
logs.Add($"File synchronization duration : {fileSynchronizationDetails.Duration}");
logger.Log(logs);
var itemOrItems = logs.Count == 1 ? "item" : "items";
reportGeneratorUtil.LogCoverageProcess($"File synchronization {logs.Count} {itemOrItems}, duration : {fileSynchronizationDetails.Duration}");
}
}
}
private void CoverageTaskCompletion(System.Threading.Tasks.Task<ReportResult> t, object state)
{
var displayCoverageResultState = (CoverageTaskState)state;
if (!IsVsShutdown)
{
switch (t.Status)
{
case System.Threading.Tasks.TaskStatus.Canceled:
LogReloadCoverageStatus(ReloadCoverageStatus.Cancelled);
reportGeneratorUtil.LogCoverageProcess("Coverage cancelled");
break;
case System.Threading.Tasks.TaskStatus.Faulted:
var innerException = t.Exception.InnerExceptions[0];
logger.Log(
StatusMarkerProvider.Get(ReloadCoverageStatus.Error.ToString()),
innerException
);
reportGeneratorUtil.LogCoverageProcess("An exception occurred. See the FCC Output Pane");
break;
case System.Threading.Tasks.TaskStatus.RanToCompletion:
LogReloadCoverageStatus(ReloadCoverageStatus.Done);
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
UpdateUI(t.Result.FileLineCoverage, t.Result.ProcessedReport);
RaiseReportFiles(t.Result);
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits
#pragma warning restore IDE0079 // Remove unnecessary suppression
break;
}
reportGeneratorUtil.EndOfCoverageRun();
}
displayCoverageResultState.CleanUp?.Invoke();
displayCoverageResultState.CancellationTokenSource.Dispose();
}
private void RaiseReportFiles(ReportResult reportResult)
{
if (reportResult.HotspotsFile != null)
{
this.eventAggregator.SendMessage(new ReportFilesMessage { CoberturaFile = reportResult.CoberturaFile, HotspotsFile = reportResult.HotspotsFile });
}
}
public void RunAndProcessReport(string[] coberturaFiles, Action cleanUp = null)
{
RunCancellableCoverageTask(async (vsShutdownLinkedCancellationToken) =>
{
ReportResult reportResult = new ReportResult();
if (coberturaFiles.Any())
{
reportResult = await RunAndProcessReportAsync(coberturaFiles, vsShutdownLinkedCancellationToken);
}
return reportResult;
}, cleanUp);
}
private void RunCancellableCoverageTask(
Func<CancellationToken,System.Threading.Tasks.Task<ReportResult>> taskCreator, Action cleanUp)
{
var vsLinkedCancellationTokenSource = Reset();
var vsShutdownLinkedCancellationToken = vsLinkedCancellationTokenSource.Token;
disposeAwareTaskRunner.RunAsyncFunc(() =>
{
reloadCoverageTask = System.Threading.Tasks.Task.Run(async () =>
{
var result = await taskCreator(vsShutdownLinkedCancellationToken);
return result;
}, vsShutdownLinkedCancellationToken)
.ContinueWith(CoverageTaskCompletion, new CoverageTaskState { CancellationTokenSource = vsLinkedCancellationTokenSource, CleanUp = cleanUp}, System.Threading.Tasks.TaskScheduler.Default);
return reloadCoverageTask;
});
}
public void ReloadCoverage(Func<System.Threading.Tasks.Task<List<ICoverageProject>>> coverageRequestCallback)
{
RunCancellableCoverageTask(async (vsShutdownLinkedCancellationToken) =>
{
ReportResult reportResult = new ReportResult();
var coverageProjects = await coverageRequestCallback();
vsShutdownLinkedCancellationToken.ThrowIfCancellationRequested();
coverageOutputManager.SetProjectCoverageOutputFolder(coverageProjects);
var coverOutputFiles = await RunCoverageAsync(coverageProjects, vsShutdownLinkedCancellationToken);
if (coverOutputFiles.Any())
{
reportResult = await RunAndProcessReportAsync(coverOutputFiles, vsShutdownLinkedCancellationToken);
}
return reportResult;
},null);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing && cancellationTokenSource != null)
{
cancellationTokenSource.Dispose();
}
disposed = true;
}
}
}
}