-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneratedCodeTestHelper.cs
More file actions
72 lines (57 loc) · 2.38 KB
/
GeneratedCodeTestHelper.cs
File metadata and controls
72 lines (57 loc) · 2.38 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
namespace EasySourceGenerators.Tests;
internal static class GeneratedCodeTestHelper
{
private const char UnicodeBom = '\uFEFF';
internal static string ReadGeneratedCode(string generatedFileName)
{
string rawCode = ReadGeneratedCodeRaw(generatedFileName);
return StripGeneratedPreamble(rawCode);
}
internal static string ReadGeneratedCodeRaw(string generatedFileName)
{
string generatedCodePath = GetGeneratedCodePath(generatedFileName);
return File.ReadAllText(generatedCodePath).TrimStart(UnicodeBom).ReplaceLineEndings("\n").TrimEnd();
}
private static string StripGeneratedPreamble(string generatedCode)
{
string[] lines = generatedCode.Split('\n');
int index = 0;
while (index < lines.Length)
{
string currentLine = lines[index];
bool isGeneratedPreambleLine = currentLine.StartsWith("//", StringComparison.Ordinal)
|| currentLine.StartsWith("#pragma warning disable", StringComparison.Ordinal)
|| string.IsNullOrWhiteSpace(currentLine);
if (!isGeneratedPreambleLine)
{
break;
}
index++;
}
return string.Join('\n', lines[index..]).TrimEnd();
}
private static string GetGeneratedCodePath(string generatedFileName)
{
string projectDirectory = FindProjectDirectory();
string[] generatedFiles = Directory.GetFiles(projectDirectory, generatedFileName, SearchOption.AllDirectories);
if (generatedFiles.Length == 0)
{
throw new AssertionException($"Could not find expected generated file '{generatedFileName}' under {projectDirectory}{Path.DirectorySeparatorChar}**");
}
return generatedFiles[0];
}
private static string FindProjectDirectory()
{
string? currentDirectory = TestContext.CurrentContext.TestDirectory;
while (currentDirectory is not null)
{
string projectFilePath = Path.Combine(currentDirectory, "EasySourceGenerators.Tests.csproj");
if (File.Exists(projectFilePath))
{
return currentDirectory;
}
currentDirectory = Directory.GetParent(currentDirectory)?.FullName;
}
throw new DirectoryNotFoundException("Could not locate EasySourceGenerators.Tests project directory.");
}
}