forked from elastic/elasticsearch-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringExtensions.cs
327 lines (287 loc) · 12.5 KB
/
StringExtensions.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Newtonsoft.Json;
namespace DocGenerator
{
public static class StringExtensions
{
private static readonly Regex LeadingSpacesAndAsterisk = new Regex(@"^(?<value>[ \t]*\*\s?).*", RegexOptions.Compiled);
private static readonly Regex LeadingMultiLineComment = new Regex(@"^(?<value>[ \t]*\/\*)", RegexOptions.Compiled);
private static readonly Regex TrailingMultiLineComment = new Regex(@"(?<value>\*\/[ \t]*)$", RegexOptions.Compiled);
public static string PascalToHyphen(this string input)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
return Regex.Replace(
Regex.Replace(
Regex.Replace(input, @"([A-Z]+)([A-Z][a-z])", "$1-$2"), @"([a-z\d])([A-Z])", "$1-$2")
, @"[-\s]+", "-", RegexOptions.Compiled).TrimEnd('-').ToLower();
}
public static string LowercaseHyphenToPascal(this string lowercaseHyphenatedInput)
{
return Regex.Replace(
lowercaseHyphenatedInput.Replace("-", " "),
@"\b([a-z])",
m => m.Captures[0].Value.ToUpper());
}
public static string TrimEnd(this string input, string trim)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
return input.EndsWith(trim, StringComparison.OrdinalIgnoreCase)
? input.Substring(0, input.Length - trim.Length)
: input;
}
public static string RemoveLeadingAndTrailingMultiLineComments(this string input)
{
var match = LeadingMultiLineComment.Match(input);
if (match.Success)
{
input = input.Substring(match.Groups["value"].Value.Length);
}
match = TrailingMultiLineComment.Match(input);
if (match.Success)
{
input = input.Substring(0, input.Length - match.Groups["value"].Value.Length);
}
return input;
}
public static string RemoveLeadingSpacesAndAsterisk(this string input)
{
var match = LeadingSpacesAndAsterisk.Match(input);
if (match.Success)
{
input = input.Substring(match.Groups["value"].Value.Length);
}
return input;
}
///<summary>
/// Removes the specified number of tabs (or spaces, assuming 4 spaces = 1 tab)
/// from each line of the input
/// </summary>
public static string RemoveNumberOfLeadingTabsOrSpacesAfterNewline(this string input, int numberOfTabs)
{
var leadingCharacterIndex = input.IndexOf("\t", StringComparison.OrdinalIgnoreCase);
if (leadingCharacterIndex == -1)
{
leadingCharacterIndex = input.IndexOf(" ", StringComparison.OrdinalIgnoreCase);
if (leadingCharacterIndex == -1)
{
return input;
}
}
int count = 0;
char firstNonTabCharacter = char.MinValue;
for (int i = leadingCharacterIndex; i < input.Length; i++)
{
if (input[i] != '\t' && input[i] != ' ')
{
firstNonTabCharacter = input[i];
count = i - leadingCharacterIndex;
break;
}
}
if (firstNonTabCharacter == '{' && numberOfTabs != count)
{
numberOfTabs = count;
}
return Regex.Replace(
Regex.Replace(
input,
$"(?<tabs>[\n|\r\n]+\t{{{numberOfTabs}}})",
m => m.Value.Replace("\t", string.Empty)
),
$"(?<spaces>[\n|\r\n]+\\s{{{numberOfTabs * 4}}})",
m => m.Value.Replace(" ", string.Empty)
);
}
public static string[] SplitOnNewLines(this string input, StringSplitOptions options)
{
return input.Split(new[] { "\r\n", "\n" }, options);
}
// TODO: Total Hack of replacements in anonymous types that represent json. This can be resolved by referencing tests assembly when building the dynamic assembly,
// but might want to put doc generation at same directory level as Tests to reference project directly.
private static Dictionary<string, string> Substitutions = new Dictionary<string, string>
{
{ "FixedDate", "new DateTime(2015, 06, 06, 12, 01, 02, 123)" },
{ "FirstNameToFind", "\"pierce\"" },
{ "Project.First.Suggest.Context.Values.SelectMany(v => v).First()", "\"red\"" },
{ "Project.First.Suggest.Contexts.Values.SelectMany(v => v).First()", "\"red\"" },
{ "Project.Instance.Name", "\"Durgan LLC\"" },
{ "Project.InstanceAnonymous", "new {name = \"Koch, Collier and Mohr\", state = \"BellyUp\",startedOn = " +
"\"2015-01-01T00:00:00\",lastActivity = \"0001-01-01T00:00:00\",leadDeveloper = " +
"new { gender = \"Male\", id = 0, firstName = \"Martijn\", lastName = \"Laarman\" }," +
"location = new { lat = 42.1523, lon = -80.321 }}" },
{ "_templateString", "\"{ \\\"match\\\": { \\\"text\\\": \\\"{{query_string}}\\\" } }\"" },
{ "base.QueryJson", "new{ @bool = new { must = new[] { new { match_all = new { } } }, must_not = new[] { new { match_all = new { } } }, should = new[] { new { match_all = new { } } }, filter = new[] { new { match_all = new { } } }, minimum_should_match = 1, boost = 2.0, } }" },
{ "ExpectedTerms", "new [] { \"term1\", \"term2\" }" },
{ "_ctxNumberofCommits", "\"_source.numberOfCommits > 0\"" },
{ "Project.First.Name", "\"Lesch Group\"" },
{ "Project.First.NumberOfCommits", "775" },
{ "LastNameSearch", "\"Stokes\"" },
{ "First.Language", "\"painless\"" },
{ "First.Init", "\"params._agg.map = [:]\"" },
{ "First.Map", "\"if (params._agg.map.containsKey(doc['state'].value)) params._agg.map[doc['state'].value] += 1 else params._agg.map[doc['state'].value] = 1;\"" },
{ "First.Reduce", "\"def reduce = [:]; for (agg in params._aggs) { for (entry in agg.map.entrySet()) { if (reduce.containsKey(entry.getKey())) reduce[entry.getKey()] += entry.getValue(); else reduce[entry.getKey()] = entry.getValue(); } } return reduce;\"" },
{ "Second.Language", "\"painless\"" },
{ "Second.Combine", "\"def sum = 0.0; for (c in params._agg.commits) { sum += c } return sum\"" },
{ "Second.Init", "\"params._agg.commits = []\"" },
{ "Second.Map", "\"if (doc['state'].value == \\\"Stable\\\") { params._agg.commits.add(doc['numberOfCommits'].value) }\"" },
{ "Second.Reduce", "\"def sum = 0.0; for (a in params._aggs) { sum += a } return sum\"" },
{ "Script.Lang", "\"painless\"" },
{ "Script.Init", "\"params._agg.commits = []\"" },
{ "Script.Map", "\"if (doc['state'].value == \\\"Stable\\\") { params._agg.commits.add(doc['numberOfCommits'].value) }\"" },
{ "Script.Combine", "\"def sum = 0.0; for (c in params._agg.commits) { sum += c } return sum\"" },
{ "Script.Reduce", "\"def sum = 0.0; for (a in params._aggs) { sum += a } return sum\"" },
{ "EnvelopeCoordinates", @"new [] { new [] { 45.0, -45.0 }, new [] { -45.0, 45.0 }}" },
{ "CircleCoordinates", @"new [] { 45.0, -45.0 }" },
{ "MultiPointCoordinates", @"new [] { new [] {38.897676, -77.03653}, new [] {38.889939, -77.009051} }" },
{ "MultiLineStringCoordinates", @"new[]
{
new [] { new [] { 2.0, 12.0 }, new [] { 2.0, 13.0 },new [] { 3.0, 13.0 }, new []{ 3.0, 12.0 } },
new [] { new [] { 0.0, 10.0 }, new [] { 0.0, 11.0 },new [] { 1.0, 11.0 }, new []{ 1.0, 10.0 } },
new [] { new [] { 0.2, 10.2 }, new [] { 0.2, 10.8 },new [] { 0.8, 10.8 }, new []{ 0.8, 12.0 } },
}" },
{ "MultiPolygonCoordinates", @"new[]
{
new []
{
new []
{
new [] { 10.0, -17.0},
new [] {15.0, 16.0},
new [] {0.0, 12.0},
new [] {-15.0, 16.0},
new [] { -10.0, -17.0},
new [] { 10.0, -17.0}
},
new []
{
new [] {8.2 , 18.2},
new [] { 8.2 , -18.8},
new [] { -8.8, -10.8},
new [] {8.8 , 18.2}
}
},
new []
{
new []
{
new [] { 8.0, -15.0},
new [] {15.0, 16.0},
new [] {0.0, 12.0},
new [] {-15.0, 16.0},
new [] { -10.0, -17.0},
new [] { 8.0, -15.0}
}
}
}" },
{ "PolygonCoordinates", @"new[]{
new []{ new [] {10.0, -17.0}, new [] {15.0, 16.0}, new [] {0.0, 12.0}, new [] {-15.0, 16.0}, new [] {-10.0, -17.0},new [] {10.0, -17.0}},
new []{ new [] {8.2, 18.2}, new [] {8.2, -18.8}, new [] {-8.8, -10.8}, new [] {8.8, 18.2}}
}" },
{ "LineStringCoordinates", @"new [] { new [] {38.897676, -77.03653}, new [] {38.889939, -77.009051} }" },
{ "PointCoordinates", "new[] { 38.897676, -77.03653 }" },
};
public static bool TryGetJsonForAnonymousType(this string anonymousTypeString, out string json)
{
json = null;
foreach (var substitution in Substitutions)
{
anonymousTypeString = anonymousTypeString.Replace(substitution.Key, substitution.Value);
}
var text =
$@"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Temporary
{{
public class Json
{{
public string Write()
{{
var o = {anonymousTypeString};
var json = JsonConvert.SerializeObject(o, Formatting.Indented);
return json;
}}
}}
}}";
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var assemblyName = Path.GetRandomFileName();
var references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(JsonConvert).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(ITypedList).GetTypeInfo().Assembly.Location),
};
var systemReferences = new string[]
{
"System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.ObjectModel, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Dynamic.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Linq.Expressions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51"
};
foreach (var r in systemReferences)
{
var location = Assembly.Load(r).Location;
references.Add(MetadataReference.CreateFromFile(location));
}
var compilation =
CSharpCompilation.Create(
assemblyName,
new[] { syntaxTree },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
var result = compilation.Emit(ms);
if (!result.Success)
{
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
var builder = new StringBuilder($"Unable to serialize the following C# anonymous type string to json: {anonymousTypeString}");
foreach (var diagnostic in failures)
{
builder.AppendLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
}
builder.AppendLine(new string('-', 30));
Console.Error.WriteLine(builder.ToString());
return false;
}
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
var type = assembly.GetType("Temporary.Json");
var obj = Activator.CreateInstance(type);
var output = type.InvokeMember("Write",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
new object[] { });
json = output.ToString();
return true;
}
}
public static string ReplaceArityWithGenericSignature(this string value)
{
var indexOfBackTick = value.IndexOf("`");
if (indexOfBackTick == -1)
return value;
var arity = value[indexOfBackTick + 1];
value = value.Substring(0, indexOfBackTick);
return Enumerable.Range(1, int.Parse(arity.ToString()))
.Aggregate(value + "<", (l, i) => l = l + (i == 1 ? "T" : $"T{i}")) + ">";
}
}
}