Skip to content

Commit

Permalink
Merge pull request #1730 from microsoftgraph/dev
Browse files Browse the repository at this point in the history
Merge dev into master
  • Loading branch information
millicentachieng committed Aug 23, 2023
2 parents 5e280f5 + 2e74ed4 commit 9103728
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 45 deletions.
10 changes: 5 additions & 5 deletions CodeSnippetsReflection.OpenAPI.Test/GraphCliGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,8 @@ public void GeneratesSnippetsForCommandWithConflictingPathAndHeaderParameterName
}

[Theory]
[InlineData("?$select=name", " --select name")]
[InlineData("?$filter=test&$select=name", " --filter test --select name")]
[InlineData("?$select=name", " --select \"name\"")]
[InlineData("?$filter=test&$select=name", " --filter \"test\" --select \"name\"")]
public async Task GeneratesSnippetsForCommandWithODataParameters(string queryString, string commandOptions)
{
// Given
Expand Down Expand Up @@ -306,7 +306,7 @@ public void GeneratesSnippetsForCommandWithQueryParameters()

// Then
// TODO: What should happen to the query parameter?
Assert.Equal(notice + Environment.NewLine + "mgc tests get --id 10", result);
Assert.Equal(notice + Environment.NewLine + "mgc tests get --id \"10\"", result);
}

[Theory]
Expand Down Expand Up @@ -494,7 +494,7 @@ public async Task GeneratesSnippetsWithExpandQueryOptions()
var result = _generator.GenerateCodeSnippet(snippetModel);

// Then
Assert.Equal(notice + Environment.NewLine + "mgc users messages get --user-id {user-id} --message-id {message-id} --expand \"singleValueExtendedProperties(`$filter=id eq 'XXXX')\"", result);
Assert.Equal(notice + Environment.NewLine + "mgc users messages get --user-id {user-id} --message-id {message-id} --expand \"singleValueExtendedProperties(\\$filter=id eq 'XXXX')\"", result);
}
[Fact]
public async Task GeneratesSnippetsWithFilterQueryOptions()
Expand Down Expand Up @@ -523,6 +523,6 @@ public async Task GeneratesSnippetsForHttpSnippetsWithUrlEncodedValuesForSystemQ
var result = _generator.GenerateCodeSnippet(snippetModel);

// Then
Assert.Equal(notice + Environment.NewLine + "mgc teams members list --team-id {team-id} --filter \"(microsoft.graph.aadUserConversationMember/displayName eq 'Harry Johnson' or microsoft.graph.aadUserConversationMember/email eq 'admin@M365x987948.OnMicrosoft.com')\"", result);
Assert.Equal(notice + Environment.NewLine + "mgc teams members list --team-id {team-id} --filter \"(microsoft.graph.aadUserConversationMember/displayName%20eq%20'Harry%20Johnson'%20or%20microsoft.graph.aadUserConversationMember/email%20eq%20'admin@M365x987948.OnMicrosoft.com')\"", result);
}
}
9 changes: 5 additions & 4 deletions CodeSnippetsReflection.OpenAPI.Test/PhpGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net.Http;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CodeSnippetsReflection.OpenAPI.LanguageGenerators;
Expand Down Expand Up @@ -144,8 +145,8 @@ public async Task GenerateForGroupPostTestSpacing()
};
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.Contains("$requestBody = new Group();\n" +
"$requestBody->setDescription('Self help community for library');\n" +
Assert.Contains($"$requestBody = new Group();{Environment.NewLine}" +
$"$requestBody->setDescription('Self help community for library');{Environment.NewLine}" +
"$requestBody->setDisplayName('Library Assist');", result);
}
[Fact]
Expand Down Expand Up @@ -874,7 +875,7 @@ public async Task GenerateWithComplexArray()
};
var snippetModel = new SnippetModel(requestPayload, ServiceRootUrl, await GetV1SnippetMetadata());
var result = _generator.GenerateCodeSnippet(snippetModel);
Assert.Contains("'owners@odata.bind' => [\n"+
Assert.Contains($"'owners@odata.bind' => [{Environment.NewLine}"+
"'https://graph.microsoft.com/v1.0/users/26be1845-4119-4801-a799-aea79d09f1a2', ],", result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public partial class GraphCliGenerator : ILanguageGenerator<SnippetModel, OpenAp
private static readonly Regex overloadedBoundedFunctionWithSingleOrMultipleParameters = new(@"\w+\([a-zA-Z,={}'-]+\)", RegexOptions.Compiled, TimeSpan.FromSeconds(5));
private static readonly Regex overloadedBoundedHyphenatedFunctionWithSingleOrMultipleParameters = new(@"(?:\w+-)+\w+\([a-zA-Z,={}'-]+\)", RegexOptions.Compiled, TimeSpan.FromSeconds(5));
private static readonly Regex unBoundFunctionRegex = new(@"^[0-9a-zA-Z\- \/_?:.,\s]+\(\)", RegexOptions.Compiled, TimeSpan.FromSeconds(5));
private static readonly Regex systemQueryOptionRegex = new(@"\w*=\w*\(\D*|\d*\)", RegexOptions.Compiled, TimeSpan.FromSeconds(5));


private const string PathItemsKey = "default";

public string GenerateCodeSnippet(SnippetModel snippetModel)
Expand Down Expand Up @@ -185,8 +184,8 @@ private static void FetchOverLoadedBoundFunctions(List<string> commandSegments,
/// <param name="segment"></param>
/// <param name="operation"></param>
/// <returns></returns>
private static (string,string) ProcessOverloadedBoundFunctions(string segment, string operation)
{
private static (string, string) ProcessOverloadedBoundFunctions(string segment, string operation)
{
StringBuilder parameterBuilder = new StringBuilder();
StringBuilder SegmentBuilder = new StringBuilder();
var functionItems = segment.Split("(");
Expand All @@ -198,8 +197,8 @@ private static (string,string) ProcessOverloadedBoundFunctions(string segment, s
foreach (var parameter in parameters)
{
var parameterValue = parameter.Split("=")[0];
var updateSegmentDetails = !parameterValue.Contains("-id")? parameterValue + " {" + parameterValue + "-id}" : parameterValue + " {" + parameterValue + "}";
parameterBuilder.Append(parameters.Length>1?$"--{updateSegmentDetails} ": $"--{updateSegmentDetails}");
var updateSegmentDetails = !parameterValue.Contains("-id") ? parameterValue + " {" + parameterValue + "-id}" : parameterValue + " {" + parameterValue + "}";
parameterBuilder.Append(parameters.Length > 1 ? $"--{updateSegmentDetails} " : $"--{updateSegmentDetails}");
var updatedSegment = $"-with-{parameterValue}";
SegmentBuilder.Append(updatedSegment);
}
Expand Down Expand Up @@ -231,32 +230,36 @@ private static void ProcessMeSegments(List<string> commandSegments, string opera
private static IDictionary<string, string> ProcessQueryParameters([NotNull] in SnippetModel snippetModel)
{
IDictionary<string, string> splitQueryString = new Dictionary<string, string>();

if (!string.IsNullOrWhiteSpace(snippetModel.QueryString))
{
if (systemQueryOptionRegex.IsMatch(snippetModel.QueryString))
{
string pattern = "\\?\\$\\w*=";
string[] splittedQueryString = Regex.Split(snippetModel.QueryString, pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(5));
string queryOptionFunction = HttpUtility.UrlDecode(splittedQueryString[1]);
var match = Regex.Match(snippetModel.QueryString, pattern, RegexOptions.Compiled, TimeSpan.FromSeconds(5));
string queryOption = match.Groups[0].Value.Replace("?", string.Empty, StringComparison.OrdinalIgnoreCase).Replace("=", string.Empty, StringComparison.OrdinalIgnoreCase);
queryOptionFunction = queryOptionFunction.Replace("$", "`$", StringComparison.OrdinalIgnoreCase);
queryOptionFunction = queryOptionFunction.Replace(queryOptionFunction, "\"" + queryOptionFunction + "\"", StringComparison.Ordinal);
splitQueryString.Add(queryOption, queryOptionFunction);
}
else
{
splitQueryString = snippetModel.QueryString
.Remove(0, 1)
.Split('&')
.Select(static q =>
splitQueryString = snippetModel.QueryString
.Remove(0, 1)
.Split('&')
.Select(static q =>
{
if (q.Contains("("))
{
var x = q.Split('=');
return x.Length > 1 ? (x[0], x[1]) : (x[0], string.Empty);
})
.Where(static t => !string.IsNullOrWhiteSpace(t.Item2))
.ToDictionary(static t => t.Item1, static t => t.Item2);
}
var qs = q;
int fl = q.Length;
qs = qs.Substring(0, qs.IndexOf("("));
int isl = qs.Length;
StringBuilder sb = new();
for (int i = isl; i < fl; i++)
{
sb.Append(q[i]);
}
var xs = qs.Split("=");
return xs.Length > 1 ? (xs[0], xs[1] + sb.Replace("$", "\\$")) : (xs[0], string.Empty);
}
var x = q.Split('=');
return x.Length > 1 ? (x[0], x[1]) : (x[0], string.Empty);
})
.Where(static t => !string.IsNullOrWhiteSpace(t.Item2))
.ToDictionary(static t => t.Item1, static t => t.Item2);

}

return splitQueryString;
Expand Down Expand Up @@ -394,7 +397,7 @@ private static void AddParameterToDictionary([NotNull] ref Dictionary<string, st
}
else
{
parameters.Add(key, paramValue);
parameters.Add(key, !paramValue.Contains("{") ? $"\"{paramValue}\"" : paramValue);
}
}

Expand Down Expand Up @@ -456,7 +459,7 @@ private static string NormalizeToOption(in string input)
return result.ToLower();
}

[GeneratedRegex("(?<=[a-z])([A-Z])", RegexOptions.Compiled)]
[GeneratedRegex("(?<=[0-9a-z])([A-Z])", RegexOptions.Compiled)]
private static partial Regex CamelCaseRegex();

[GeneratedRegex("(?<=[a-z])[-_\\.]+([A-Za-z])", RegexOptions.Compiled)]
Expand Down
1 change: 1 addition & 0 deletions PermissionsService/Services/PermissionsStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ private async Task<string> FetchHttpSourceDocument(string sourceUri)
RequestUrl = request.RequestUrl,
Message = exception.Message
});
_telemetryClient?.TrackException(exception);
}
});

Expand Down
15 changes: 10 additions & 5 deletions UriMatchService/UriTemplateMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public TemplateMatch Match(Uri uri)
{
if (parameters.Count == 0)
return new TemplateMatch() { Key = template.Key, Template = template.Value }; // exact match, no ids
else
else if (!templateMatches.ContainsKey(template))
templateMatches.Add(template, parameters.Count);
}
}
Expand Down Expand Up @@ -112,13 +112,18 @@ public TemplateMatch Match(Uri uri)
{
Regex parameterRegex = null;

if (parameterRegex == null)
int count = 0;
template = placeholderRegex.Replace(template, m => $"{{{++count}}}");
var matchingRegex = CreateMatchingRegex(template);

try
{
int count = 0;
template = placeholderRegex.Replace(template, m => $"{{{++count}}}");
var matchingRegex = CreateMatchingRegex(template);
parameterRegex = new Regex(matchingRegex, RegexOptions.None, TimeSpan.FromSeconds(5));
}
catch (Exception)
{
return null;

Check warning on line 125 in UriMatchService/UriTemplateMatcher.cs

View workflow job for this annotation

GitHub Actions / Build

Return an empty collection instead of null. (https://rules.sonarsource.com/csharp/RSPEC-1168)
}

var match = parameterRegex.Match(uri.OriginalString);
var parameters = new Dictionary<string, string>();
Expand Down

0 comments on commit 9103728

Please sign in to comment.