Skip to content

Commit

Permalink
Merge pull request #3423 from andreaTP/py-name-mangling-in-refiners
Browse files Browse the repository at this point in the history
[Python] Move (most of) the name mangling logic into the refiner
  • Loading branch information
baywet authored Oct 10, 2023
2 parents db7f477 + f0b3e2a commit d0e9439
Show file tree
Hide file tree
Showing 15 changed files with 258 additions and 170 deletions.
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Refiners/CommonLanguageRefiner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1309,7 +1309,7 @@ public void AddQueryParameterMapperMethod(CodeElement currentElement, string met
{
if (currentElement is CodeClass currentClass &&
currentClass.IsOfKind(CodeClassKind.QueryParameters) &&
currentClass.Properties.Any(static x => x.IsNameEscaped))
currentClass.Properties.Any(static x => x.IsNameEscaped && !x.SerializationName.Equals(x.Name, StringComparison.Ordinal)))
{
var method = currentClass.AddMethod(new CodeMethod
{
Expand Down
63 changes: 60 additions & 3 deletions src/Kiota.Builder/Refiners/PythonRefiner.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -16,6 +17,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
return Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
CorrectCommonNames(generatedCode);
RemoveMethodByKind(generatedCode, CodeMethodKind.RawUrlConstructor);
AddDefaultImports(generatedCode, defaultUsingEvaluators);
DisableActionOf(generatedCode,
Expand Down Expand Up @@ -43,7 +45,7 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
AddPropertiesAndMethodTypesImports(generatedCode, true, true, true, codeTypeFilter);
AddParsableImplementsForModelClasses(generatedCode, "Parsable");
cancellationToken.ThrowIfCancellationRequested();
ReplaceBinaryByNativeType(generatedCode, "bytes", string.Empty);
ReplaceBinaryByNativeType(generatedCode, "bytes", string.Empty, true);
ReplaceReservedNames(
generatedCode,
new PythonReservedNamesProvider(),
Expand All @@ -68,10 +70,12 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
MoveClassesWithNamespaceNamesUnderNamespace(generatedCode);
ReplacePropertyNames(generatedCode,
new() {
CodePropertyKind.AdditionalData,
CodePropertyKind.Custom,
CodePropertyKind.QueryParameter,
CodePropertyKind.RequestBuilder,
},
static s => s.ToSnakeCase());
static s => s.ToFirstCharacterLowerCase().ToSnakeCase());
AddParentClassToErrorClasses(
generatedCode,
"APIError",
Expand Down Expand Up @@ -114,7 +118,9 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
$"{AbstractionsPackageName}.serialization.ParseNodeFactoryRegistry" });
cancellationToken.ThrowIfCancellationRequested();
AddQueryParameterMapperMethod(
generatedCode
generatedCode,
"get_query_parameter",
"original_name"
);
AddDiscriminatorMappingsUsingsToParentClasses(
generatedCode,
Expand Down Expand Up @@ -158,6 +164,56 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
new (static x => x is CodeClass { OriginalComposedType: CodeIntersectionType intersectionType } && intersectionType.Types.Any(static y => !y.IsExternal) && intersectionType.DiscriminatorInformation.HasBasicDiscriminatorInformation,
$"{AbstractionsPackageName}.serialization", "ParseNodeHelper"),
};

private static void CorrectCommonNames(CodeElement currentElement)
{
if (currentElement is CodeMethod m &&
currentElement.Parent is CodeClass parentClassM)
{
parentClassM.RenameChildElement(m.Name, m.Name.ToFirstCharacterLowerCase().ToSnakeCase());

foreach (var param in m.Parameters)
{
param.Name = param.Name.ToFirstCharacterLowerCase().ToSnakeCase();
}
}
else if (currentElement is CodeClass c)
{
c.Name = c.Name.ToFirstCharacterUpperCase();
}
else if (currentElement is CodeProperty p &&
(p.IsOfKind(CodePropertyKind.RequestAdapter) ||
p.IsOfKind(CodePropertyKind.PathParameters) ||
p.IsOfKind(CodePropertyKind.QueryParameters) ||
p.IsOfKind(CodePropertyKind.UrlTemplate)) &&
currentElement.Parent is CodeClass parentClassP)
{
if (p.SerializationName != null)
p.SerializationName = p.Name;

parentClassP.RenameChildElement(p.Name, p.Name.ToFirstCharacterLowerCase().ToSnakeCase());
}
else if (currentElement is CodeIndexer i)
{
i.IndexParameter.Name = i.IndexParameter.Name.ToFirstCharacterLowerCase().ToSnakeCase();
}
else if (currentElement is CodeEnum e)
{
foreach (var option in e.Options)
{
if (!string.IsNullOrEmpty(option.Name) && Char.IsLower(option.Name[0]))
{
if (string.IsNullOrEmpty(option.SerializationName))
{
option.SerializationName = option.Name;
}
option.Name = option.Name.ToCamelCase().ToFirstCharacterUpperCase();
}
}
}

CrawlTree(currentElement, element => CorrectCommonNames(element));
}
private static void CorrectImplements(ProprietableBlockDeclaration block)
{
block.Implements.Where(x => "IAdditionalDataHolder".Equals(x.Name, StringComparison.OrdinalIgnoreCase)).ToList().ForEach(x => x.Name = x.Name[1..]); // skipping the I
Expand All @@ -184,6 +240,7 @@ private static void CorrectPropertyType(CodeProperty currentProperty)
if (!string.IsNullOrEmpty(currentProperty.DefaultValue))
currentProperty.DefaultValue = "{}";
}
currentProperty.Type.Name = currentProperty.Type.Name.ToFirstCharacterUpperCase();
CorrectCoreTypes(currentProperty.Parent as CodeClass, DateTypesReplacements, currentProperty.Type);
}
private static void CorrectMethodType(CodeMethod currentMethod)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,13 @@ public override void WriteCodeElement(ClassDeclaration codeElement, LanguageWrit
}
}

var abcClass = !codeElement.Implements.Any() ? string.Empty : $"{codeElement.Implements.Select(static x => x.Name.ToFirstCharacterUpperCase()).Aggregate((x, y) => x + ", " + y)}";
var abcClass = !codeElement.Implements.Any() ? string.Empty : $"{codeElement.Implements.Select(static x => x.Name).Aggregate((x, y) => x + ", " + y)}";
var derivation = codeElement.Inherits is CodeType inheritType &&
conventions.GetTypeString(inheritType, codeElement) is string inheritSymbol &&
!string.IsNullOrEmpty(inheritSymbol) ?
inheritSymbol :
abcClass;
writer.WriteLine($"class {codeElement.Name.ToFirstCharacterUpperCase()}({derivation}):");
writer.WriteLine($"class {codeElement.Name}({derivation}):");
writer.IncreaseIndent();
if (codeElement.Parent is CodeClass parent)
{
Expand Down
4 changes: 2 additions & 2 deletions src/Kiota.Builder/Writers/Python/CodeEnumWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write
ArgumentNullException.ThrowIfNull(writer);
writer.WriteLine("from enum import Enum");
writer.WriteLine();
writer.WriteLine($"class {codeElement.Name.ToFirstCharacterUpperCase()}(str, Enum):");
writer.WriteLine($"class {codeElement.Name}(str, Enum):");
writer.IncreaseIndent();
if (!codeElement.Options.Any())
{
Expand All @@ -25,7 +25,7 @@ public override void WriteCodeElement(CodeEnum codeElement, LanguageWriter write
codeElement.Options.ToList().ForEach(x =>
{
conventions.WriteInLineDescription(x.Documentation.Description, writer);
writer.WriteLine($"{x.Name.ToFirstCharacterUpperCase()} = \"{x.WireName}\",");
writer.WriteLine($"{x.Name} = \"{x.WireName}\",");
});
}
}
Expand Down
Loading

0 comments on commit d0e9439

Please sign in to comment.