Skip to content

Commit

Permalink
refactor name tracking for variables
Browse files Browse the repository at this point in the history
  • Loading branch information
ramsessanchez committed Sep 20, 2023
1 parent 46347d2 commit cb0783c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
4 changes: 2 additions & 2 deletions CodeSnippetsReflection.OpenAPI.Test/JavaGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ public async Task GeneratesObjectsInArray()
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.Contains("com.microsoft.graph.users.item.assignlicense.AssignLicensePostRequestBody assignLicensePostRequestBody = new com.microsoft.graph.users.item.assignlicense.AssignLicensePostRequestBody();", result);
Assert.Contains("LinkedList<UUID> disabledPlans0 = new LinkedList<UUID>", result);
Assert.Contains("LinkedList<UUID> disabledPlans = new LinkedList<UUID>", result);
Assert.Contains("LinkedList<UUID> removeLicenses = new LinkedList<UUID>", result);
Assert.Contains("UUID.fromString(\"bea13e0c-3828-4daa-a392-28af7ff61a0f\")", result);
}
Expand Down Expand Up @@ -816,7 +816,7 @@ public async Task GeneratesCorrectCollectionTypeAndDerivedInstances()
Assert.Contains("SendMailPostRequestBody sendMailPostRequestBody = new com.microsoft.graph.users.item.sendmail.SendMailPostRequestBody()", result);
Assert.Contains("LinkedList<Attachment> attachments = new LinkedList<Attachment>", result);// Collection defines Base type
Assert.Contains("new FileAttachment", result);// Individual items are derived types
Assert.Contains("byte[] contentBytes0 = Base64.getDecoder().decode(\"SGVsbG8gV29ybGQh\")", result);
Assert.Contains("byte[] contentBytes = Base64.getDecoder().decode(\"SGVsbG8gV29ybGQh\")", result);
}

[Fact]
Expand Down
37 changes: 22 additions & 15 deletions CodeSnippetsReflection.OpenAPI/LanguageGenerators/JavaGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public string GenerateCodeSnippet(SnippetModel snippetModel)
var snippetBuilder = new StringBuilder($"// Code snippets are only available for the latest version. Current version is 6.x{Environment.NewLine}{Environment.NewLine}" +
$"{ClientVarType} {ClientVarName} = new {ClientVarType}({HttpCoreVarName});{Environment.NewLine}{Environment.NewLine}");

WriteRequestPayloadAndVariableName(codeGraph, snippetBuilder, indentManager);
WriteRequestPayloadAndVariableName(codeGraph, snippetBuilder);
WriteRequestExecutionPath(codeGraph, snippetBuilder, indentManager);
return snippetBuilder.ToString();
}
Expand Down Expand Up @@ -278,20 +278,18 @@ private static string GetPathParameterDeclaration(CodeProperty pathParameter, st
private static string ReplaceIfReservedName(string originalString, string suffix = "Object")
=> ReservedNames.Contains(originalString) ? $"{originalString}{suffix}" : originalString;

private static void WriteRequestPayloadAndVariableName(SnippetCodeGraph snippetCodeGraph, StringBuilder snippetBuilder, IndentManager indentManager)
private static void WriteRequestPayloadAndVariableName(SnippetCodeGraph snippetCodeGraph, StringBuilder snippetBuilder)
{
if (!snippetCodeGraph.HasBody())
return;// No body

if (indentManager == null)
throw new ArgumentNullException(nameof(indentManager));

switch (snippetCodeGraph.Body.PropertyType)
{
case PropertyType.Object:
var typeString = GetTypeString(snippetCodeGraph.Body, snippetCodeGraph.ApiVersion);
snippetBuilder.AppendLine($"{typeString} {GetPropertyObjectName(snippetCodeGraph.Body).ToFirstCharacterLowerCase()} = new {typeString}();");
snippetCodeGraph.Body.Children.ForEach( child => WriteObjectFromCodeProperty(snippetCodeGraph.Body, child, snippetBuilder, indentManager,snippetCodeGraph.ApiVersion));
var objectName = GetPropertyObjectName(snippetCodeGraph.Body).ToFirstCharacterLowerCase();
List<string> usedVariableNames = new List<string>() {objectName};
snippetBuilder.AppendLine($"{typeString} {objectName} = new {typeString}();");
snippetCodeGraph.Body.Children.ForEach( child => WriteObjectFromCodeProperty(snippetCodeGraph.Body, child, snippetBuilder,snippetCodeGraph.ApiVersion, objectName, usedVariableNames));
break;
case PropertyType.Binary:
snippetBuilder.AppendLine($"ByteArrayInputStream stream = new ByteArrayInputStream(new byte[0]); //stream to upload");
Expand All @@ -301,12 +299,12 @@ private static void WriteRequestPayloadAndVariableName(SnippetCodeGraph snippetC
}
}

private static void WriteObjectFromCodeProperty(CodeProperty parentProperty, CodeProperty codeProperty, StringBuilder snippetBuilder, IndentManager indentManager, string apiVersion, string parentEnumerableValue = "", string currentEnumerableValue = "")
private static void WriteObjectFromCodeProperty(CodeProperty parentProperty, CodeProperty codeProperty, StringBuilder snippetBuilder, string apiVersion, string parentPropertyName, List<string> usedVariableNames)
{
var setterPrefix = "set";
var typeString = GetTypeString(codeProperty, apiVersion);
var currentPropertyName = $"{GetPropertyObjectName(codeProperty) ?? "property"}{currentEnumerableValue}";
var parentPropertyName = $"{GetPropertyObjectName(parentProperty) ?? "parentProperty"}{parentEnumerableValue}";
var currentPropertyName = EnsureJavaVariableNameIsUnique($"{GetPropertyObjectName(codeProperty) ?? "property"}", usedVariableNames);
usedVariableNames.Add(currentPropertyName);

var isParentArray = parentProperty.PropertyType == PropertyType.Array;
var isParentMap = parentProperty.PropertyType == PropertyType.Map;
Expand All @@ -317,21 +315,19 @@ private static void WriteObjectFromCodeProperty(CodeProperty parentProperty, Cod

var assignment = $"{propertyAssignment}{currentPropertyName.ToFirstCharacterLowerCase() ?? "property"});";

parentEnumerableValue = currentEnumerableValue == "" ? string.Empty : currentEnumerableValue;

switch (codeProperty.PropertyType)
{
case PropertyType.Object:
snippetBuilder.AppendLine($"{typeString} {currentPropertyName.ToFirstCharacterLowerCase()} = new {typeString}();");
codeProperty.Children.ForEach(child => WriteObjectFromCodeProperty(codeProperty, child, snippetBuilder, indentManager, apiVersion, parentEnumerableValue, currentEnumerableValue));
codeProperty.Children.ForEach(child => WriteObjectFromCodeProperty(codeProperty, child, snippetBuilder, apiVersion, currentPropertyName, usedVariableNames));
snippetBuilder.AppendLine(assignment);
break;
case PropertyType.Array:
case PropertyType.Map:
snippetBuilder.AppendLine($"{typeString} {currentPropertyName.ToFirstCharacterLowerCase()} = new {typeString}();");
var childEnumerationValue = 0;
codeProperty.Children.ForEach(child => {
WriteObjectFromCodeProperty(codeProperty, child, snippetBuilder, indentManager, apiVersion, parentEnumerableValue, $"{childEnumerationValue}");
WriteObjectFromCodeProperty(codeProperty, child, snippetBuilder, apiVersion, currentPropertyName, usedVariableNames);
childEnumerationValue++;
});
snippetBuilder.AppendLine(assignment);
Expand Down Expand Up @@ -456,6 +452,17 @@ private static string GetNamespaceName(string namespaceName, string apiVersion)
return $"com.{GetDefaultNamespaceName(apiVersion)}.{normalizedNameSpaceName.Replace("me.", "users.item.")}.";
}

private static string EnsureJavaVariableNameIsUnique(string variableName, List<string> usedVariableNames)
{
var count = usedVariableNames.Count(x => x.Equals(variableName));
if (count > 0)
{
return $"{variableName}{count}";//append the count to the end of string since we've used it before
}
return variableName;
}


private static string GetDefaultNamespaceName(string apiVersion) =>
apiVersion.Equals("beta", StringComparison.OrdinalIgnoreCase) ? $"{DefaultNamespace}.beta" : DefaultNamespace;
}
Expand Down

0 comments on commit cb0783c

Please sign in to comment.