-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSourceCodeWriter.cs
More file actions
91 lines (75 loc) · 2.29 KB
/
SourceCodeWriter.cs
File metadata and controls
91 lines (75 loc) · 2.29 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
using System;
using System.CodeDom.Compiler;
using System.IO;
namespace Generator;
public sealed class SourceCodeWriter : IDisposable
{
private static string StartBlockText => "{";
private static string EndBlockText => "}";
private readonly IndentedTextWriter _indentingStringWriter;
public SourceCodeWriter()
{
var stringWriter = new StringWriter();
_indentingStringWriter = new IndentedTextWriter(stringWriter, " ");
}
public void WriteLine(string s)
{
_indentingStringWriter.WriteLine(s);
}
public IDisposable WriteBlock(string statement)
{
WriteLine(statement);
return BeginWriteBlock();
}
public IDisposable BeginWriteBlock(string statement = "")
{
if (StartBlockText is not null)
{
_indentingStringWriter.WriteLine(StartBlockText);
}
return IndentAndWriteLineAtEndOfIndent(EndBlockText + statement);
}
public void WriteNewLine()
{
var currentIndentation = _indentingStringWriter.Indent;
_indentingStringWriter.Indent = 0;
_indentingStringWriter.WriteLine();
_indentingStringWriter.Indent = currentIndentation;
}
public IDisposable Indent()
{
_indentingStringWriter.Indent++;
return new IndentDisposable(_indentingStringWriter);
}
public IDisposable IndentAndWriteLineAtEndOfIndent(string s)
{
_indentingStringWriter.Indent++;
return new IndentDisposable(_indentingStringWriter, s);
}
public void Dispose()
{
_indentingStringWriter.Dispose();
}
public override string ToString()
{
return _indentingStringWriter.InnerWriter.ToString() ?? "";
}
private class IndentDisposable : IDisposable
{
private readonly IndentedTextWriter _indentingStringWriter;
private readonly string? _line;
public IndentDisposable(IndentedTextWriter indentingStringWriter, string? line = null)
{
_indentingStringWriter = indentingStringWriter;
_line = line;
}
public void Dispose()
{
_indentingStringWriter.Indent--;
if (_line is not null)
{
_indentingStringWriter.WriteLine(_line);
}
}
}
}