-
Notifications
You must be signed in to change notification settings - Fork 7
/
StaticResourceGenerator.cs
214 lines (176 loc) · 5.01 KB
/
StaticResourceGenerator.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
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace Sylvan.BuildTools.Resources
{
public class StaticResourceGenerator : Task
{
[Required]
// The folder where we will write all of our generated code.
public string OutputPath { get; set; }
// The folders to generate types from.
public ITaskItem[] InputFolders { get; set; }
public string Namespace { get; set; }
// Will contain all of the generated coded we create
[Output]
public ITaskItem[] OutputCode { get; set; }
bool hasError = false;
const string AccessPublic = "Public";
// The method that is called to invoke our task.
public override bool Execute()
{
if (InputFolders == null)
return true;
var outCodeItems = new List<TaskItem>();
var generatorType = this.GetType();
string generatorName = generatorType.FullName;
string generatorVersion = generatorType.GetTypeInfo().Assembly.GetName().Version.ToString();
// loop over all the folders
foreach (var folder in InputFolders)
{
if (!Directory.Exists(folder.ItemSpec))
{
this.Log.LogError($"StaticResourceFolder {folder.ItemSpec} does not exist.");
continue;
}
var root = Path.GetFileName(folder.ItemSpec);
Directory.CreateDirectory(OutputPath);
var codeFile = Path.Combine(OutputPath, folder.ItemSpec + ".g.cs");
var access = folder.GetMetadata("AccessModifier");
var isPublic = StringComparer.OrdinalIgnoreCase.Equals(access, AccessPublic);
var ns = folder.GetMetadata("Namespace");
ns = string.IsNullOrWhiteSpace(ns) ? Namespace : ns;
outCodeItems.Add(new TaskItem(codeFile));
Directory.CreateDirectory(Path.GetDirectoryName(codeFile));
using (var oStream = new FileStream(codeFile, FileMode.Create))
using (var w = new StreamWriter(oStream))
{
if (!string.IsNullOrEmpty(ns))
{
w.WriteLine($"namespace {ns} {{");
w.WriteLine();
}
w.WriteLine($@"[global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{generatorName}"", ""{generatorVersion}"")]");
WriteClass(w, folder.ItemSpec, isPublic);
if (!string.IsNullOrEmpty(ns))
{
w.WriteLine("}");
w.WriteLine();
}
}
}
// put the artifacts we created in the output properties.
OutputCode = outCodeItems.ToArray();
return !hasError;
}
void WriteClass(TextWriter w, string folder, bool isPublic, int depth = 0)
{
var className = Path.GetFileNameWithoutExtension(folder);
className = IdentifierStyle.PascalCase.Convert(className);
// very simplistic resource accessor class mostly duplicated from resx output.
w.Write($@"
/// <summary>
/// A static resource class, for looking up strings, etc.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCode()]
{((isPublic || depth > 0) ? "public " : string.Empty)}static partial class {className}
{{
");
w.Write($@"
/// <summary>
/// Allow some custom string processing.
/// </summary>
static partial void PreProcess(ref string s);
static string Process(string str)
{{
PreProcess(ref str);
return str;
}}
");
foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.TopDirectoryOnly))
{
var name = Path.GetFileNameWithoutExtension(file);
name = IdentifierStyle.PascalCase.Convert(name);
var comment = $"Gets the string contents of {Path.GetFileName(file)}.";
if (comment != null)
{
IEnumerable<string> commentLines = comment.Split(new[] { "\r", "\n", "\r\n" }, StringSplitOptions.None);
w.Write($@"
/// <summary>
/// {string.Join(Environment.NewLine + " /// ", commentLines)}.
/// </summary>");
}
var str = CSharpStringEscape(File.ReadAllText(file));
w.Write($@"
public static readonly string {name} = Process(""{str}"");
");
foreach(var child in Directory.EnumerateDirectories(folder))
{
WriteClass(w, child, isPublic, depth + 1);
}
}
w.WriteLine("}");
}
static string CSharpStringEscape(string str)
{
var sb = new StringBuilder();
foreach (char c in str)
{
switch (c)
{
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\'':
sb.Append("\\'");
break;
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\a':
sb.Append("\\a");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\t':
sb.Append("\\t");
break;
case '\v':
sb.Append("\\v");
break;
case '\0':
sb.Append("\\0");
break;
default:
// if it is a printable ASCII,
// write it verbatim
if (c >= ' ' && c <= 127)
{
sb.Append(c);
}
else
{
sb.Append("\\u");
sb.Append(((int)c).ToString("X4"));
}
break;
}
}
return sb.ToString();
}
}
}