forked from microsoft/kiota
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRubyRefiner.cs
More file actions
307 lines (302 loc) · 16.2 KB
/
Copy pathRubyRefiner.cs
File metadata and controls
307 lines (302 loc) · 16.2 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Kiota.Builder.CodeDOM;
using Kiota.Builder.Configuration;
using Kiota.Builder.Extensions;
using Kiota.Builder.PathSegmenters;
namespace Kiota.Builder.Refiners;
public partial class RubyRefiner : CommonLanguageRefiner, ILanguageRefiner
{
public RubyRefiner(GenerationConfiguration configuration) : base(configuration) { }
public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken cancellationToken)
{
return Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
RemoveMethodByKind(generatedCode, CodeMethodKind.RawUrlConstructor);
DeduplicateErrorMappings(generatedCode);
ReplaceIndexersByMethodsWithParameter(generatedCode,
false,
static x => $"by_{x.ToSnakeCase()}",
static x => x.ToSnakeCase(),
GenerationLanguage.Ruby);
MoveRequestBuilderPropertiesToBaseType(generatedCode,
new CodeUsing
{
Name = "MicrosoftKiotaAbstractions::BaseRequestBuilder",
Declaration = new CodeType
{
Name = "MicrosoftKiotaAbstractions",
IsExternal = true
}
});
RemoveRequestConfigurationClasses(generatedCode);
DisambiguateClassesWithNamespaceNames(generatedCode, "Model");
ConvertUnionTypesToWrapper(generatedCode,
_configuration.UsesBackingStore,
static s => s,
false
);
var reservedNamesProvider = new RubyReservedNamesProvider();
CorrectNames(generatedCode, s =>
{
if (s.Contains('_', StringComparison.OrdinalIgnoreCase) &&
s.ToPascalCase(UnderscoreArray) is string refinedName &&
!reservedNamesProvider.ReservedNames.Contains(s) &&
!reservedNamesProvider.ReservedNames.Contains(refinedName))
return refinedName;
else
return s;
}, false, true);
cancellationToken.ThrowIfCancellationRequested();
if (generatedCode.FindNamespaceByName(_configuration.ModelsNamespaceName) is CodeNamespace modelsNS)
FlattenModelsNamespaces(modelsNS, modelsNS);
AddPropertiesAndMethodTypesImports(generatedCode, false, false, true);
RemoveCancellationParameter(generatedCode);
cancellationToken.ThrowIfCancellationRequested();
AddParsableImplementsForModelClasses(generatedCode, "MicrosoftKiotaAbstractions::Parsable");
AddDefaultImports(generatedCode, defaultUsingEvaluators);
RemoveUntypedNodeTypeValues(generatedCode);
CorrectCoreType(generatedCode, CorrectMethodType, CorrectPropertyType, CorrectImplements);
cancellationToken.ThrowIfCancellationRequested();
ReplacePropertyNames(generatedCode,
[
CodePropertyKind.Custom,
CodePropertyKind.QueryParameter,
],
static s => s.ToSnakeCase());
AddParentClassToErrorClasses(
generatedCode,
"ApiError",
"MicrosoftKiotaAbstractions",
true
);
ReplaceReservedNames(generatedCode, reservedNamesProvider, x => $"{x}_escaped");
AddGetterAndSetterMethods(generatedCode,
[
CodePropertyKind.Custom,
CodePropertyKind.AdditionalData,
CodePropertyKind.BackingStore,
],
static (_, s) => s.ToSnakeCase(),
_configuration.UsesBackingStore,
true,
string.Empty,
string.Empty,
string.Empty);
AddConstructorsForDefaultValues(
generatedCode,
true,
false,
[CodeClassKind.RequestConfiguration]);
ShortenLongNamespaceNames(generatedCode);
if (generatedCode.FindNamespaceByName(_configuration.ClientNamespaceName)?.Parent is CodeNamespace parentOfClientNS)
AddNamespaceModuleImports(parentOfClientNS, generatedCode);
var defaultConfiguration = new GenerationConfiguration();
cancellationToken.ThrowIfCancellationRequested();
ReplaceDefaultSerializationModules(
generatedCode,
defaultConfiguration.Serializers,
new(StringComparer.OrdinalIgnoreCase) {
"microsoft_kiota_serialization_json.JsonSerializationWriterFactory"});
ReplaceDefaultDeserializationModules(
generatedCode,
defaultConfiguration.Deserializers,
new(StringComparer.OrdinalIgnoreCase) {
"microsoft_kiota_serialization_json.JsonParseNodeFactory"});
AddSerializationModulesImport(generatedCode,
["microsoft_kiota_abstractions.ApiClientBuilder",
"microsoft_kiota_abstractions.SerializationWriterFactoryRegistry"],
["microsoft_kiota_abstractions.ParseNodeFactoryRegistry"]);
AddQueryParameterMapperMethod(
generatedCode
);
cancellationToken.ThrowIfCancellationRequested();
AddDiscriminatorMappingsUsingsToParentClasses(
generatedCode,
"ParseNode",
addUsings: true
);
}, cancellationToken);
}
private static void ShortenLongNamespaceNames(CodeElement currentElement)
{
if (currentElement is CodeNamespace currentNamespace &&
!string.IsNullOrEmpty(currentNamespace.Name) &&
currentNamespace.Name.Split('.', StringSplitOptions.RemoveEmptyEntries) is string[] nameParts &&
nameParts.Select(static x => x.ToSnakeCase()).Any(static x => x.Length > RubyPathSegmenter.MaxFileNameLength))
{
var newName = string.Join(".", nameParts
.Select(static x => (originalName: x, snakeName: x.ToSnakeCase()))
.Select(static x => x.snakeName.Length > RubyPathSegmenter.MaxFileNameLength ? x.originalName.GetNamespaceImportSymbol() : x.originalName));
if (currentNamespace.Parent is CodeNamespace parentNamespace)
parentNamespace.RenameChildElement(currentNamespace.Name, newName);
}
CrawlTree(currentElement, ShortenLongNamespaceNames);
}
/// <summary>
/// A model sharing its name with a sibling namespace is suffixed so the two do not collide.
/// References need no separate pass: CodeType.Name delegates to TypeDefinition.Name for a
/// resolved, non-external type, so every reference already reports the new name. A pass that
/// assigned to those names instead renamed the class again, once per reference it walked.
/// </summary>
private static void DisambiguateClassesWithNamespaceNames(CodeElement currentElement, string suffix)
{
if (currentElement is CodeClass currentClass &&
currentClass.IsOfKind(CodeClassKind.Model) &&
currentClass.Parent is CodeNamespace currentNamespace &&
currentNamespace.FindChildByName<CodeNamespace>($"{currentNamespace.Name}.{currentClass.Name}") is not null)
{
currentNamespace.RemoveChildElement(currentClass);
currentClass.Name = $"{currentClass.Name}{suffix}";
currentNamespace.AddClass(currentClass);
}
CrawlTree(currentElement, x => DisambiguateClassesWithNamespaceNames(x, suffix));
}
// `\\.` matches a literal backslash and `(<letter>...)` is an ordinary group capturing the text
// "<letter>", so the original pattern never matched and every nested model kept the dots from
// its namespace, which are not legal in a Ruby constant
[GeneratedRegex(@"\.(?<letter>\w)", RegexOptions.IgnoreCase | RegexOptions.Singleline, 500)]
private static partial Regex CapitalizedFirstLetterAfterDot();
private static void FlattenModelsNamespaces(CodeElement currentElement, CodeNamespace modelsNS)
{
// only classes and enums are moved up to the models namespace; without this guard any other
// child, a nested namespace included, was still detached and renamed but never re-added,
// which corrupted the prefix computed for every element visited afterwards
if (currentElement is CodeClass or CodeEnum &&
currentElement.Parent is CodeNamespace currentElementNamespace &&
currentElementNamespace.IsChildOf(modelsNS))
{
var elementPrefix = CapitalizedFirstLetterAfterDot().Replace(currentElementNamespace.Name[(modelsNS.Name.Length + 1)..], x => x.Groups["letter"].Value.ToUpperInvariant());
currentElementNamespace.RemoveChildElement(currentElement);
currentElement.Name = $"{elementPrefix}{currentElement.Name.ToFirstCharacterUpperCase()}";
if (currentElement is CodeClass currentClass)
modelsNS.AddClass(currentClass);
else if (currentElement is CodeEnum currentEnum)
modelsNS.AddEnum(currentEnum);
}
CrawlTree(currentElement, x => FlattenModelsNamespaces(x, modelsNS));
}
private static void CorrectMethodType(CodeMethod currentMethod)
{
if (currentMethod.IsOfKind(CodeMethodKind.Factory) && currentMethod.Parameters.OfKind(CodeParameterKind.ParseNode) is CodeParameter parseNodeParam)
parseNodeParam.Type.Name = parseNodeParam.Type.Name[1..];
CorrectCoreTypes(currentMethod.Parent as CodeClass, DateTypesReplacements, types: currentMethod.Parameters
.Select(x => x.Type)
.Union(new[] { currentMethod.ReturnType })
.ToArray());
}
private static readonly Dictionary<string, (string, CodeUsing?)> DateTypesReplacements = new(StringComparer.OrdinalIgnoreCase) {
{"DateTimeOffset", ("DateTime", new CodeUsing {
Name = "DateTime",
Declaration = new CodeType {
Name = "date",
IsExternal = true,
},
})},
{"TimeSpan", ("MicrosoftKiotaAbstractions::ISODuration", new CodeUsing {
Name = "MicrosoftKiotaAbstractions::ISODuration",
Declaration = new CodeType {
Name = "microsoft_kiota_abstractions",
IsExternal = true,
},
})},
{"DateOnly", ("Date", new CodeUsing {
Name = "Date",
Declaration = new CodeType {
Name = "date",
IsExternal = true,
},
})},
{"TimeOnly", ("Time", new CodeUsing {
Name = "Time",
Declaration = new CodeType {
Name = "time",
IsExternal = true,
},
})},
};
private static void CorrectPropertyType(CodeProperty currentProperty)
{
if (currentProperty.IsOfKind(CodePropertyKind.PathParameters, CodePropertyKind.AdditionalData))
{
currentProperty.Type.IsNullable = true;
if (!string.IsNullOrEmpty(currentProperty.DefaultValue))
currentProperty.DefaultValue = "Hash.new";
}
CorrectCoreTypes(currentProperty.Parent as CodeClass, DateTypesReplacements, types: currentProperty.Type);
}
private static readonly AdditionalUsingEvaluator[] defaultUsingEvaluators = {
new (static x => x is CodeProperty prop && prop.IsOfKind(CodePropertyKind.RequestAdapter),
"microsoft_kiota_abstractions", "RequestAdapter"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestGenerator),
"microsoft_kiota_abstractions", "HttpMethod", "RequestInformation", "RequestOption"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestExecutor),
"microsoft_kiota_abstractions", "ResponseHandler"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.Serializer),
"microsoft_kiota_abstractions", "SerializationWriter"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.Deserializer),
"microsoft_kiota_abstractions", "ParseNode"),
new (static x => x is CodeClass @class && @class.IsOfKind(CodeClassKind.Model),
"microsoft_kiota_abstractions", "Parsable"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.RequestExecutor),
"microsoft_kiota_abstractions", "Parsable"),
new (static x => x is CodeClass @class && @class.IsOfKind(CodeClassKind.Model) && @class.Properties.Any(static y => y.IsOfKind(CodePropertyKind.AdditionalData)),
"microsoft_kiota_abstractions", "AdditionalDataHolder"),
new (static x => x is CodeMethod method && method.IsOfKind(CodeMethodKind.ClientConstructor) &&
method.Parameters.Any(static y => y.IsOfKind(CodeParameterKind.BackingStore)),
"microsoft_kiota_abstractions", "BackingStoreFactory", "BackingStoreFactorySingleton"),
new (static x => x is CodeProperty prop && prop.IsOfKind(CodePropertyKind.BackingStore),
"microsoft_kiota_abstractions", "BackingStore", "BackedModel", "BackingStoreFactorySingleton" ),
};
private static void AddInheritedAndMethodTypesImports(CodeElement currentElement)
{
if (currentElement is CodeClass currentClass && currentClass.IsOfKind(CodeClassKind.Model)
&& currentClass.StartBlock.Inherits != null)
{
currentClass.AddUsing(new CodeUsing { Name = currentClass.StartBlock.Inherits.Name, Declaration = currentClass.StartBlock.Inherits });
}
CrawlTree(currentElement, AddInheritedAndMethodTypesImports);
}
private static void AddNamespaceModuleImports(CodeNamespace clientNamespaceParent, CodeElement current)
{
if (current is CodeClass currentClass)
{
var module = currentClass.GetImmediateParentOfType<CodeNamespace>();
AddModules(clientNamespaceParent, module, (usingToAdd) =>
{
currentClass.AddUsing(usingToAdd);
});
}
CrawlTree(current, c => AddNamespaceModuleImports(clientNamespaceParent, c));
}
private static void AddModules(CodeNamespace clientNamespaceParent, CodeNamespace module, Action<CodeUsing> callback)
{
var definition = module;
while (definition != clientNamespaceParent && !string.IsNullOrEmpty(definition?.Name))
{
callback(new CodeUsing
{
Name = definition.Name,
Declaration = new CodeType
{
IsExternal = false,
Name = definition.Name,
TypeDefinition = definition,
}
});
definition = definition.Parent as CodeNamespace;
}
}
private static void CorrectImplements(ProprietableBlockDeclaration block)
{
block.Implements
.Where(static x => "IAdditionalDataHolder".Equals(x.Name, StringComparison.OrdinalIgnoreCase))
.ToList()
.ForEach(static x => x.Name = "MicrosoftKiotaAbstractions::AdditionalDataHolder");
}
}