-
Notifications
You must be signed in to change notification settings - Fork 161
/
StringExtensions.cs
396 lines (352 loc) · 13.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Humanizer;
using Humanizer.Inflections;
using Microsoft.CodeAnalysis.CSharp;
namespace AutoRest.CSharp.Utilities
{
internal static class StringExtensions
{
static StringExtensions()
{
Vocabularies.Default.AddUncountable("data");
}
public static bool IsNullOrEmpty(this string? text) => String.IsNullOrEmpty(text);
public static bool IsNullOrWhiteSpace(this string? text) => String.IsNullOrWhiteSpace(text);
[return: NotNullIfNotNull("name")]
public static string ToCleanName(this string name, bool camelCase = true)
{
StringBuilder nameBuilder = new StringBuilder();
int i = 0;
if (char.IsDigit(name[0]))
{
nameBuilder.Append("_");
}
else
{
while (!SyntaxFacts.IsIdentifierStartCharacter(name[i]))
{
i++;
}
}
bool upperCase = false;
for (; i < name.Length; i++)
{
var c = name[i];
if (!SyntaxFacts.IsIdentifierPartCharacter(c) || c == '_')
{
upperCase = true;
continue;
}
if (nameBuilder.Length == 0)
{
c = camelCase ? char.ToUpper(c) : char.ToLower(c);
upperCase = false;
}
if (upperCase)
{
c = char.ToUpper(c);
upperCase = false;
}
nameBuilder.Append(c);
}
return nameBuilder.ToString();
}
[return: NotNullIfNotNull("name")]
public static string ToVariableName(this string name) => ToCleanName(name, camelCase: false);
public static GetPathPartsEnumerator GetPathParts(string? path) => new GetPathPartsEnumerator(path);
public ref struct GetPathPartsEnumerator
{
private ReadOnlySpan<char> _path;
public Part Current { get; private set; }
public GetPathPartsEnumerator(ReadOnlySpan<char> path)
{
_path = path;
Current = default;
}
public GetPathPartsEnumerator GetEnumerator() => this;
public bool MoveNext()
{
var span = _path;
if (span.Length == 0)
{
return false;
}
var separatorIndex = span.IndexOfAny('{', '}');
if (separatorIndex == -1)
{
Current = new Part(span, true);
_path = ReadOnlySpan<char>.Empty;
return true;
}
var separator = span[separatorIndex];
// Handle {{ and }} escape sequences
if (separatorIndex + 1 < span.Length && span[separatorIndex + 1] == separator)
{
Current = new Part(span.Slice(0, separatorIndex + 1), true);
_path = span.Slice(separatorIndex + 2);
return true;
}
var isLiteral = separator == '{';
// Skip empty literals
if (isLiteral && separatorIndex == 0 && span.Length > 1)
{
separatorIndex = span.IndexOf('}');
if (separatorIndex == -1)
{
Current = new Part(span.Slice(1), true);
_path = ReadOnlySpan<char>.Empty;
return true;
}
Current = new Part(span.Slice(1, separatorIndex - 1), false);
}
else
{
Current = new Part(span.Slice(0, separatorIndex), isLiteral);
}
_path = span.Slice(separatorIndex + 1);
return true;
}
public readonly ref struct Part
{
public Part(ReadOnlySpan<char> span, bool isLiteral)
{
Span = span;
IsLiteral = isLiteral;
}
public ReadOnlySpan<char> Span { get; }
public bool IsLiteral { get; }
public void Deconstruct(out ReadOnlySpan<char> span, out bool isLiteral)
{
span = Span;
isLiteral = IsLiteral;
}
}
}
public static bool IsCSharpKeyword(string? name)
{
switch (name)
{
case "abstract":
case "add":
case "alias":
case "as":
case "ascending":
case "async":
case "await":
case "base":
case "bool":
case "break":
case "by":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "descending":
case "do":
case "double":
case "dynamic":
case "else":
case "enum":
case "equals":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "from":
case "get":
case "global":
case "goto":
// `group` is a contextual to linq queries that we don't generate
//case "group":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "into":
case "is":
case "join":
case "let":
case "lock":
case "long":
case "nameof":
case "namespace":
case "new":
case "null":
case "object":
case "on":
case "operator":
// `orderby` is a contextual to linq queries that we don't generate
//case "orderby":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
// `select` is a contextual to linq queries that we don't generate
// case "select":
case "set":
case "short":
case "sizeof":
case "stackalloc":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unchecked":
case "unmanaged":
case "unsafe":
case "ushort":
case "using":
// `value` is a contextual to getters that we don't generate
// case "value":
case "var":
case "virtual":
case "void":
case "volatile":
case "when":
case "where":
case "while":
case "yield":
return true;
default:
return false;
}
}
public static string ToPlural(this string single, bool inputIsKnownToBeSingular = true)
{
return single.Pluralize(inputIsKnownToBeSingular);
}
private static string LastWordToPlural(this string single, bool inputIsKnownToBeSingular = true)
{
var words = single.SplitByCamelCase();
var lastWord = words.LastOrDefault();
var lastWordPlural = lastWord.Pluralize(inputIsKnownToBeSingular);
if (inputIsKnownToBeSingular || lastWord != lastWordPlural)
{
return single.ReplaceLast(lastWord, lastWordPlural);
}
return single;
}
public static string ToSingular(this string plural, bool inputIsKnownToBePlural = true)
{
return plural.Singularize(inputIsKnownToBePlural);
}
private static string LastWordToSingular(this string plural, bool inputIsKnownToBePlural = true)
{
var words = plural.SplitByCamelCase();
var lastWord = words.LastOrDefault();
var lastWordSingular = lastWord.Singularize(inputIsKnownToBePlural);
if (inputIsKnownToBePlural || lastWord != lastWordSingular)
{
return plural.ReplaceLast(lastWord, lastWordSingular);
}
return plural;
}
public static string FirstCharToLowerCase(this string str)
{
if (string.IsNullOrEmpty(str) || char.IsLower(str[0]))
return str;
return char.ToLower(str[0]) + str.Substring(1);
}
public static string FirstCharToUpperCase(this string str)
{
if (string.IsNullOrEmpty(str) || char.IsUpper(str[0]))
return str;
return char.ToUpper(str[0]) + str.Substring(1);
}
public static IEnumerable<string> SplitByCamelCase(this string camelCase)
{
return camelCase.Humanize().Split(' ').Select(w => w.FirstCharToUpperCase());
}
public static StringBuilder AppendIndentation(this StringBuilder builder, int indentation)
{
var indent = new string(' ', indentation);
return builder.Append(indent);
}
//https://stackoverflow.com/a/8809437/294804
public static string ReplaceFirst(this string text, string oldValue, string newValue)
{
var position = text.IndexOf(oldValue, StringComparison.Ordinal);
return position < 0 ? text : text.Substring(0, position) + newValue + text.Substring(position + oldValue.Length);
}
public static string ReplaceLast(this string text, string oldValue, string newValue)
{
var position = text.LastIndexOf(oldValue, StringComparison.Ordinal);
return position < 0 ? text : text.Substring(0, position) + newValue + text.Substring(position + oldValue.Length);
}
public static string RenameListToGet(this string methodName, string resourceName)
{
var newName = methodName;
if (methodName.Equals("List") || methodName.Equals("ListAll") || methodName.StartsWith("ListBy"))
{
var pluralResourceName = resourceName.LastWordToPlural(inputIsKnownToBeSingular: false);
var singularResourceName = resourceName.LastWordToSingular(inputIsKnownToBePlural: false);
var getMethodPrefix = pluralResourceName == singularResourceName ? "GetAll" : "Get";
var wordToBeReplaced = methodName.StartsWith("ListBy") ? "List" : methodName;
newName = methodName.ReplaceFirst(wordToBeReplaced, $"{getMethodPrefix}{pluralResourceName}");
}
else if (methodName.StartsWith("List"))
{
var words = methodName.SplitByCamelCase();
var getMethodPrefix = "Get";
// Cases like ListEntitiesAssignedWithTerm is difficult to parse which noun should be plural and will just make no changes to the nouns for now.
if (!words.Any(w => new HashSet<string> { "By", "With" }.Contains(w)))
{
var pluralMethodName = methodName.LastWordToPlural(inputIsKnownToBeSingular: false);
var singularMethodName = methodName.LastWordToSingular(inputIsKnownToBePlural: false);
if (pluralMethodName == singularMethodName)
{
getMethodPrefix = "GetAll";
}
newName = pluralMethodName;
}
newName = newName.ReplaceFirst("List", getMethodPrefix);
}
return newName;
}
public static string RenameGetMethod(this string methodName, string resourceName)
{
if (methodName.Equals("Get"))
{
return $"Get{resourceName.LastWordToSingular(inputIsKnownToBePlural: false)}";
}
return methodName;
}
}
}