-
-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathEmitter.cs
More file actions
89 lines (74 loc) · 3.08 KB
/
Emitter.cs
File metadata and controls
89 lines (74 loc) · 3.08 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
class Emitter
{
const string AutoGenerationHeader = """
//-----------------------------------------------------
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior
// and will be lost when the code is regenerated.
// <auto-generated />
//-----------------------------------------------------
""";
static readonly string GeneratedCodeAttribute =
$"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{typeof(Emitter).Assembly.GetName().Name}\", \"{typeof(Emitter).Assembly.GetName().Version}\")]";
readonly IndentedStringBuilder builder = new();
void WriteNamespace(ClassToGenerate classToGenerate)
{
if (classToGenerate.Namespace is not null)
{
builder.Append("namespace ").AppendLine(classToGenerate.Namespace)
.AppendLine("{")
.IncreaseIndent();
}
WriteParentTypes(classToGenerate);
if (classToGenerate.Namespace is not null)
{
builder.DecreaseIndent()
.AppendLine("}");
}
}
void WriteParentTypes(ClassToGenerate classToGenerate)
{
foreach (var parentClass in classToGenerate.ParentClasses)
{
builder.Append("partial ").Append(parentClass.Keyword).Append(" ").AppendLine(parentClass.Name)
.AppendLine("{");
builder.IncreaseIndent();
}
WriteClass(classToGenerate);
foreach (var _ in classToGenerate.ParentClasses)
{
builder.DecreaseIndent()
.AppendLine("}");
}
}
void WriteClass(ClassToGenerate classToGenerate) =>
builder.Append("partial class ").AppendLine(classToGenerate.ClassName)
.AppendLine("{")
.IncreaseIndent()
.AppendLine(GeneratedCodeAttribute)
.Append("public ")
.Append(TestContextModifiers(classToGenerate))
.AppendLine("global::Microsoft.VisualStudio.TestTools.UnitTesting.TestContext TestContext")
.AppendLine("{")
.IncreaseIndent()
.AppendLine("get => global::VerifyMSTest.Verifier.CurrentTestContext.Value!.TestContext;")
.AppendLine("set => global::VerifyMSTest.Verifier.CurrentTestContext.Value = new global::VerifyMSTest.TestExecutionContext(value, GetType());")
.DecreaseIndent()
.AppendLine("}")
.DecreaseIndent()
.AppendLine("}");
public string GenerateExtensionClasses(IReadOnlyCollection<ClassToGenerate> classesToGenerate, Cancel cancel)
{
builder.AppendLine(AutoGenerationHeader);
foreach (var classToGenerate in classesToGenerate)
{
cancel.ThrowIfCancellationRequested();
builder.AppendLine();
WriteNamespace(classToGenerate);
}
return builder.ToString();
}
static string TestContextModifiers(ClassToGenerate classToGenerate)
=> classToGenerate.OverrideTestContext ? "override " : string.Empty;
}