-
-
Notifications
You must be signed in to change notification settings - Fork 724
/
SingleFileDocumentWriter.cs
70 lines (59 loc) · 2.04 KB
/
SingleFileDocumentWriter.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
using System;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using IOPath = System.IO.Path;
namespace StrawberryShake.CodeGeneration.CSharp.Analyzers
{
public class SingleFileDocumentWriter : IDocumentWriter
{
private StringBuilder _content = new();
private GeneratorExecutionContext? _execution;
private string? _fileName;
private bool _emitCode;
public void WriteDocument(ClientGeneratorContext context, SourceDocument document)
{
string documentName = $"{document.Name}.cs";
context.Log.WriteDocument(documentName);
_content.AppendLine("// " + documentName);
_content.AppendLine(document.SourceText);
_content.AppendLine();
if (context.OutputFiles && _fileName is null)
{
_fileName = IOPath.Combine(
context.OutputDirectory,
$"{context.Settings.Name}.StrawberryShake.cs");
_emitCode = context.Settings.EmitGeneratedCode;
context.FileNames.Add(_fileName);
}
if (!_execution.HasValue)
{
_execution = context.Execution;
}
}
public void Flush()
{
if (_execution is null)
{
return;
}
_execution.Value.AddSource(
IOPath.GetFileName(_fileName),
SourceText.From(_content.ToString(), Encoding.UTF8));
if (_emitCode && _fileName is not null)
{
string directory = IOPath.GetDirectoryName(_fileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
if (File.Exists(_fileName))
{
File.Delete(_fileName);
}
File.WriteAllText(_fileName, _content.ToString(), Encoding.UTF8);
}
}
}
}