/
InstrumentationHelper.cs
250 lines (203 loc) · 8.4 KB
/
InstrumentationHelper.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.PortableExecutable;
using System.Text.RegularExpressions;
using Microsoft.Extensions.FileSystemGlobbing;
using Microsoft.Extensions.FileSystemGlobbing.Abstractions;
namespace Coverlet.Core.Helpers
{
internal static class InstrumentationHelper
{
public static string[] GetCoverableModules(string module)
{
IEnumerable<string> modules = Directory.EnumerateFiles(Path.GetDirectoryName(module)).Where(f => f.EndsWith(".exe") || f.EndsWith(".dll"));
modules = modules.Where(m => IsAssembly(m) && Path.GetFileName(m) != Path.GetFileName(module));
return modules.ToArray();
}
public static bool HasPdb(string module)
{
using (var moduleStream = File.OpenRead(module))
using (var peReader = new PEReader(moduleStream))
{
foreach (var entry in peReader.ReadDebugDirectory())
{
if (entry.Type == DebugDirectoryEntryType.CodeView)
{
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry);
var peDirectory = Path.GetDirectoryName(module);
return File.Exists(Path.Combine(peDirectory, Path.GetFileName(codeViewData.Path)));
}
}
return false;
}
}
public static void CopyCoverletDependency(string module)
{
var moduleFileName = Path.GetFileName(module);
if (Path.GetFileName(typeof(Coverage).Assembly.Location) == moduleFileName)
return;
var directory = Path.GetDirectoryName(module);
var assembly = typeof(Coverlet.Tracker.CoverageTracker).Assembly;
File.Copy(assembly.Location, Path.Combine(directory, Path.GetFileName(assembly.Location)), true);
}
public static void BackupOriginalModule(string module, string identifier)
{
var backupPath = GetBackupPath(module, identifier);
File.Copy(module, backupPath);
}
public static void RestoreOriginalModule(string module, string identifier)
{
var backupPath = GetBackupPath(module, identifier);
// Restore the original module - retry up to 10 times, since the destination file could be locked
// See: https://github.com/tonerdo/coverlet/issues/25
var retryStrategy = CreateRetryStrategy();
RetryHelper.Retry(() =>
{
File.Copy(backupPath, module, true);
File.Delete(backupPath);
}, retryStrategy, 10);
}
public static void DeleteHitsFile(string path)
{
// Retry hitting the hits file - retry up to 10 times, since the file could be locked
// See: https://github.com/tonerdo/coverlet/issues/25
var retryStrategy = CreateRetryStrategy();
RetryHelper.Retry(() => File.Delete(path), retryStrategy, 10);
}
public static bool IsValidFilterExpression(string filter)
{
if (filter == null)
return false;
if (!filter.StartsWith("["))
return false;
if (!filter.Contains("]"))
return false;
if (filter.Count(f => f == '[') > 1)
return false;
if (filter.Count(f => f == ']') > 1)
return false;
if (filter.IndexOf(']') < filter.IndexOf('['))
return false;
if (filter.IndexOf(']') - filter.IndexOf('[') == 1)
return false;
if (filter.EndsWith("]"))
return false;
if (new Regex(@"[^\w*]").IsMatch(filter.Replace(".", "").Replace("?", "").Replace("[", "").Replace("]", "")))
return false;
return true;
}
public static bool IsModuleExcluded(string module, string[] filters)
{
if (filters == null)
return false;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (var filter in filters)
{
string modulePattern = filter.Substring(1, filter.IndexOf(']') - 1);
string typePattern = filter.Substring(filter.IndexOf(']') + 1);
if (typePattern != "*")
continue;
modulePattern = WildcardToRegex(modulePattern);
var regex = new Regex(modulePattern);
if (regex.IsMatch(module))
return true;
}
return false;
}
public static bool IsTypeExcluded(string module, string type, string[] filters)
{
if (filters == null)
return false;
module = Path.GetFileNameWithoutExtension(module);
if (module == null)
return false;
foreach (var filter in filters)
{
string typePattern = filter.Substring(filter.IndexOf(']') + 1);
string modulePattern = filter.Substring(1, filter.IndexOf(']') - 1);
typePattern = WildcardToRegex(typePattern);
modulePattern = WildcardToRegex(modulePattern);
if (new Regex(typePattern).IsMatch(type) && new Regex(modulePattern).IsMatch(module))
return true;
}
return false;
}
public static bool IsLocalMethod(string method)
=> new Regex(WildcardToRegex("<*>*__*|*")).IsMatch(method);
public static string[] GetExcludedFiles(string[] rules)
{
const string RELATIVE_KEY = nameof(RELATIVE_KEY);
string parentDir = Directory.GetCurrentDirectory();
if (rules == null || !rules.Any()) return Array.Empty<string>();
var matcherDict = new Dictionary<string, Matcher>() { { RELATIVE_KEY, new Matcher() } };
foreach (var excludeRule in rules)
{
if (Path.IsPathRooted(excludeRule))
{
var root = Path.GetPathRoot(excludeRule);
if (!matcherDict.ContainsKey(root))
{
matcherDict.Add(root, new Matcher());
}
matcherDict[root].AddInclude(excludeRule.Substring(root.Length));
}
else
{
matcherDict[RELATIVE_KEY].AddInclude(excludeRule);
}
}
var files = new List<string>();
foreach (var entry in matcherDict)
{
var root = entry.Key;
var matcher = entry.Value;
var directoryInfo = new DirectoryInfo(root.Equals(RELATIVE_KEY) ? parentDir : root);
var fileMatchResult = matcher.Execute(new DirectoryInfoWrapper(directoryInfo));
var currentFiles = fileMatchResult.Files
.Select(f => Path.GetFullPath(Path.Combine(directoryInfo.ToString(), f.Path)));
files.AddRange(currentFiles);
}
return files.Distinct().ToArray();
}
private static string GetBackupPath(string module, string identifier)
{
return Path.Combine(
Path.GetTempPath(),
Path.GetFileNameWithoutExtension(module) + "_" + identifier + ".dll"
);
}
private static Func<TimeSpan> CreateRetryStrategy(int initialSleepSeconds = 6)
{
TimeSpan retryStrategy()
{
var sleep = TimeSpan.FromMilliseconds(initialSleepSeconds);
initialSleepSeconds *= 2;
return sleep;
}
return retryStrategy;
}
private static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", "?") + "$";
}
private static bool IsAssembly(string filePath)
{
try
{
AssemblyName.GetAssemblyName(filePath);
return true;
}
catch
{
return false;
}
}
}
}