Skip to content

Commit

Permalink
Fix functions as object names in go snippets (#2051)
Browse files Browse the repository at this point in the history
* Fix functions as object names in go snippets

* fix static vars in linq
  • Loading branch information
rkodev authored May 17, 2024
1 parent 4d352d4 commit aeedd23
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 8 deletions.
14 changes: 14 additions & 0 deletions CodeSnippetsReflection.OpenAPI.Test/GoGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,20 @@ public async Task WritesEmptyPrimitiveArrays() {
Assert.Contains("SetIncludeUserActions", result);
}
[Fact]
public async Task WriteCorrectFunctionNameWithParametersAsModelName()
{
const string messageObject = "{\r\n\"displayName\": \"Display name\"\r\n}";
using var requestPayload = new HttpRequestMessage(HttpMethod.Patch, $"{ServiceRootUrl}/applications(uniqueName='app-65278')")
{
Content = new StringContent(messageObject, Encoding.UTF8, "application/json")
};
requestPayload.Headers.Add("Prefer", "create-if-missing");
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetBetaSnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.Contains("graphapplicationswithuniquename \"github.com/microsoftgraph/msgraph-sdk-go/applicationswithuniquename\"", result);
Assert.Contains("graphapplicationswithuniquename.ApplicationsWithUniqueNameRequestBuilderPatchRequestConfiguration", result);
}
[Fact]
public async Task WriteCorrectTypesForFilterParameters()
{
using var requestPayload = new HttpRequestMessage(HttpMethod.Get,
Expand Down
49 changes: 41 additions & 8 deletions CodeSnippetsReflection.OpenAPI/LanguageGenerators/GoGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using CodeSnippetsReflection.OpenAPI.ModelGraph;
using CodeSnippetsReflection.StringExtensions;
using Microsoft.OpenApi.Services;
using System.Text.RegularExpressions;
using System.Collections;

namespace CodeSnippetsReflection.OpenAPI.LanguageGenerators
{
public class GoGenerator : ILanguageGenerator<SnippetModel, OpenApiUrlTreeNode>
{
private const string clientVarName = "graphClient";
private const string clientVarType = "GraphServiceClientWithCredentials";
private const string clientFactoryVariables = "cred, scopes";
private const string requestBodyVarName = "requestBody";
private const string requestHeadersVarName = "headers";
private const string optionsParameterVarName = "options";
Expand All @@ -29,6 +27,10 @@ public class GoGenerator : ILanguageGenerator<SnippetModel, OpenApiUrlTreeNode>

private static readonly Regex PropertyNameRegex = new Regex(@"@(.*)", RegexOptions.Compiled, TimeSpan.FromMilliseconds(200));

private static readonly Regex FunctionRegex = new Regex(@"(\w+)\(([^)]*)\)", RegexOptions.Compiled, TimeSpan.FromMilliseconds(200));

private static readonly Regex ParamRegex = new Regex(@"(\w+)\s*=\s*'[^']*'", RegexOptions.Compiled, TimeSpan.FromMilliseconds(200));

static IImmutableSet<string> GetNativeTypes()
{
return ImmutableHashSet.Create("string", "int", "float");
Expand Down Expand Up @@ -142,9 +144,24 @@ private static void TraverseProperty(CodeProperty property, Action<CodeProperty>

private static String ProcessNameSpaceName(String nameSpace)
{
return (nameSpace != null ? nameSpace.Split(".", StringSplitOptions.RemoveEmptyEntries)
if (String.IsNullOrEmpty(nameSpace))
return "";

// process function names and parameters
var functionNameMatch = FunctionRegex.Match(nameSpace);
if (functionNameMatch.Success)
{
var paramMatches = ParamRegex.Matches(functionNameMatch.Groups[2].Value);
var paramNames = paramMatches.Cast<Match>().Select(static m => m.Groups[1].Value).ToList();

return functionNameMatch.Groups[1].Value + "With" + string.Join("With", paramNames);
}

var processedName = (nameSpace.Split(".", StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Equals("Me", StringComparison.OrdinalIgnoreCase) ? "Users" : x)
.Aggregate((current, next) => current + "." + next) : "models").Replace(".microsoft.graph", "");
.Aggregate(static (current, next) => current + "." + next)).Replace(".microsoft.graph", "");

return processedName;
}

private static String ProcessFinalNameSpaceName(String nameSpace)
Expand Down Expand Up @@ -306,7 +323,7 @@ private static string GetNestedObjectName(IEnumerable<OpenApiUrlTreeNode> nodes)
if (x.Segment.IsCollectionIndex())
return "Item";
else
return x.Segment.ToFirstCharacterUpperCase();
return EscapeFunctionNames(x.Segment.ToFirstCharacterUpperCase());
})
.Aggregate(static (x, y) =>
{
Expand All @@ -316,6 +333,22 @@ private static string GetNestedObjectName(IEnumerable<OpenApiUrlTreeNode> nodes)
});
}

private static string EscapeFunctionNames(String objectName)
{
if (String.IsNullOrEmpty(objectName))
return objectName;

var match = FunctionRegex.Match(objectName);
if (match.Success)
{
var paramMatches = ParamRegex.Matches(match.Groups[2].Value);
var paramNames = paramMatches.Cast<Match>().Select(static m => m.Groups[1].Value.ToFirstCharacterUpperCase()).ToList();

return match.Groups[1].Value + "With" + string.Join("With", paramNames);
}
return objectName;
}

private static string evaluateParameter(CodeProperty param)
{
if (param.PropertyType == PropertyType.Array)
Expand Down

0 comments on commit aeedd23

Please sign in to comment.